<?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 Rafa Souza Pinto on Medium]]></title>
        <description><![CDATA[Stories by Rafa Souza Pinto on Medium]]></description>
        <link>https://medium.com/@rafa.souza.pinto?source=rss-77a57203dd3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Hbq4EJpBhLHkRcUJXk_sCg@2x.jpeg</url>
            <title>Stories by Rafa Souza Pinto on Medium</title>
            <link>https://medium.com/@rafa.souza.pinto?source=rss-77a57203dd3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:29:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rafa.souza.pinto/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[What a qubit actually does, why that breaks RSA, and how to read this week’s Anthropic result]]></title>
            <link>https://medium.com/@rafa.souza.pinto/what-a-qubit-actually-does-why-that-breaks-rsa-and-how-to-read-this-weeks-anthropic-result-d09dc2c20f0f?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d09dc2c20f0f</guid>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[post-quantum-cryptography]]></category>
            <category><![CDATA[cryptography]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Thu, 03 Dec 2026 14:01:11 GMT</pubDate>
            <atom:updated>2026-12-03T14:01:11.811Z</atom:updated>
            <content:encoded><![CDATA[<p>On November 30, Anthropic released four theoretical papers on lattice cryptography. One of them describes a quantum algorithm, found with the help of unreleased Claude models, that attacks the math behind ML-KEM and ML-DSA. Those are the two main post-quantum standards NIST finalized in 2024, and the ones governments and large companies are rolling out right now.</p><p>Nothing broke. The speedup only shows up at key sizes far larger than anything deployed, and Anthropic says it still considers both standards among the strongest public key algorithms available. But it also says the result lowers its long-term confidence in structured lattices, the family of math both schemes rely on.</p><p>I spent more than 15 years building high-performance financial systems, most of that time around the Brazilian equities market. In that world TLS is something you configure once and stop thinking about.</p><p>Quantum computing is a newer subject for me, and I came to it as an engineer, not as a physicist. I started with <em>Quantum Computing for the Quantum Curious</em> (Hughes, Isaacson, Perry, Sun and Turner), which builds the intuition with very little math. Then I moved to <em>Programming Quantum Computers</em>, which treats a quantum computer as something you program. From the books I went to the simulators: Qiskit Aer, PennyLane and Amazon Braket, with experiments on real market data that I have written about here before.</p><p>This week’s news sits right where those two sides meet. So this article starts from a single qubit and walks up to the questions that matter for anyone running production systems: what post-quantum cryptography is, where it is used, and what to do about it now.</p><p>The math stays light. If you can read Python, you can follow everything here.</p><h3>One qubit, three gates</h3><p>A classical bit is 0 or 1. A qubit carries two numbers, called amplitudes, one for 0 and one for 1. When you measure it you get 0 or 1, and the probability of each is the square of its amplitude. Before the measurement both amplitudes exist, and you can operate on them.</p><p>The usual picture for one qubit is the Bloch sphere. The north pole is |0⟩ and the south pole is |1⟩. Every other point on the surface is a valid state. Points on the equator are equal mixes of 0 and 1 that differ only in phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kXxBz2_532gvbMpO1vpQFQ.png" /><figcaption><em>Figure 1. A bit has two states. A qubit can point anywhere on the sphere.</em></figcaption></figure><p>Gates are rotations of that sphere. Three of them are enough for this article.</p><p><strong>X</strong> is the quantum NOT. It rotates the state 180° around the x axis, so |0⟩ becomes |1⟩.</p><p><strong>H</strong>, the Hadamard gate, takes |0⟩ to the equator, to the state written |+⟩. Measure it and you get 0 half the time and 1 the other half.</p><p><strong>Z</strong> flips the phase. It rotates the state 180° around the z axis. The poles don’t move, but |+⟩ becomes |−⟩. Both give 50/50 when measured, so the difference is invisible until another gate acts on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grzCZO2YxIszRtAw2wrJlg.png" /><figcaption><em>Figure 2. X, H and Z as rotations of the qubit state.</em></figcaption></figure><p>That invisible phase is where the power comes from. Apply H twice to |0⟩ and the result is not more random. You get |0⟩ back, every time. The two paths that lead to 1 carry opposite signs and cancel. Put a Z between the two H gates and the cancellation moves to the other side: now you get 1 every time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSgU1ehos-ygx3kgHT7sqg.png" /><figcaption><em>Figure 3. Each circuit run 1,000 times on the Qiskit Aer simulator. One H gives a coin flip. Two give certainty.</em></figcaption></figure><p>A coin flipped twice is still random. A qubit sent through H twice is not. This is interference, and a quantum algorithm is a way of arranging it so that wrong answers cancel and the right one adds up.</p><p>The last piece is measurement. Reading a qubit destroys the amplitudes. If the state was |+⟩ and you read 0, the state is now |0⟩. You can’t look without leaving a mark, and you can’t copy an unknown qubit to inspect the copy instead. That limitation turns out to be useful.</p><h3>Catching a spy with one qubit</h3><p>The book <em>Programming Quantum Computers</em> (Johnston, Harrigan and Gimeno-Segovia, O’Reilly) has a small hands-on example in its single-qubit chapter called the Quantum Spy Hunter. It needs one qubit and only the gates above. Here is my version of the idea in Qiskit.</p><p>Alice wants to send bits to Bob. For each bit she flips a coin to decide whether to apply H before sending. Bob flips his own coin to decide whether to apply H before measuring. Afterwards they compare coins in public and keep only the rounds where they made the same choice. In those rounds H was either never applied or applied twice, so Bob reads exactly what Alice sent.</p><p>Now put a spy in the middle. She has to measure the qubit to learn anything, and she doesn’t know whether Alice applied H. Half the time she guesses wrong, collapses the state in the wrong basis, and what she forwards to Bob is random.</p><pre>import random<br>from qiskit import QuantumCircuit<br>from qiskit_aer import AerSimulator<br>sim = AerSimulator()<br>def send_qubit(spy: bool):<br>    a_bit, a_had = random.getrandbits(1), random.getrandbits(1)<br>    b_had = random.getrandbits(1)<br>    qc = QuantumCircuit(1, 2)<br>    if a_bit: qc.x(0)            # Alice encodes her bit<br>    if a_had: qc.h(0)            # ...in the basis she picked<br>    if spy:                      # the spy has to guess the basis<br>        s_had = random.getrandbits(1)<br>        if s_had: qc.h(0)<br>        qc.measure(0, 1)         # measuring collapses the state<br>        if s_had: qc.h(0)        # and she forwards what she saw<br>    if b_had: qc.h(0)            # Bob picks his own basis<br>    qc.measure(0, 0)<br>    out = sim.run(qc, shots=1, memory=True).result().get_memory()[0]<br>    b_bit = int(out[-1])<br>    return a_bit, a_had, b_bit, b_had<br>def error_rate(spy: bool, rounds: int = 20000) -&gt; float:<br>    kept = errors = 0<br>    for _ in range(rounds):<br>        a_bit, a_had, b_bit, b_had = send_qubit(spy)<br>        if a_had == b_had:       # keep only rounds where bases match<br>            kept += 1<br>            errors += a_bit != b_bit<br>    return errors / kept<br>print(f&quot;no spy:   {error_rate(False):.1%} mismatches&quot;)<br>print(f&quot;with spy: {error_rate(True):.1%} mismatches&quot;)</pre><p>On my run this printed 0.0% without the spy and 25.2% with her.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5WORq-1OQUh4NZbXTo-4A.png" /><figcaption><em>Figure 4. The spy shows up as errors in the bits Alice and Bob keep.</em></figcaption></figure><p>Without the spy, the kept rounds agree every time. With her, about one in four disagrees. Alice and Bob only need to compare a sample of their bits to know someone is listening. This is the core of BB84, the first quantum key distribution protocol.</p><p>The example shows that a measurement is a physical event with consequences, so security can come from physics and not only from a hard math problem. It is also not post-quantum cryptography. Quantum key distribution needs quantum hardware and dedicated links. Post-quantum cryptography is a different thing, and it is the one that will reach your servers.</p><h3>From one qubit to Shor</h3><p>Scale the same ingredients up. Take a register of qubits and put it in superposition with H gates. Compute a function over all inputs at once. Then use interference to make one property of that function stand out. In 1994 Peter Shor showed that this recipe finds the period of modular exponentiation efficiently, and finding that period is enough to factor large integers and to compute discrete logarithms.</p><p>RSA depends on factoring being hard. Diffie-Hellman and elliptic curve cryptography depend on discrete logarithms. Together they protect nearly every TLS handshake, VPN, code signature and certificate in use today. A large enough fault-tolerant quantum computer breaks all of them, and bigger keys don’t help.</p><p>Symmetric cryptography is in better shape. Grover’s algorithm gives a quadratic speedup on brute-force search, which roughly halves the effective key length. AES-256 and SHA-384 stay comfortable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eVSYN6sc1iPCId3QrmJvpA.png" /><figcaption><em>Figure 5. What a large quantum computer does to each family of cryptography.</em></figcaption></figure><p>No machine can run Shor against RSA-2048 today. The resource estimates keep dropping though. In 2019 the reference estimate was 20 million noisy qubits. In 2025 Craig Gidney at Google brought it under one million.</p><p>There is also a reason not to wait for the machine. Traffic recorded today can be decrypted later. If your data has to stay secret for ten years, the clock is already running. This is usually called harvest now, decrypt later.</p><h3>What post-quantum cryptography is</h3><p>Post-quantum cryptography (PQC) is classical cryptography. It runs on the CPUs we already have. What changes is the math problem underneath, chosen so that no efficient algorithm is known for it, classical or quantum.</p><p>NIST opened a public competition in 2016 and published the first three standards in August 2024:</p><ul><li><strong>ML-KEM</strong> (FIPS 203), formerly Kyber. A key encapsulation mechanism, the replacement for the key exchange in TLS. Built on module lattices.</li><li><strong>ML-DSA</strong> (FIPS 204), formerly Dilithium. Digital signatures, also on module lattices.</li><li><strong>SLH-DSA</strong> (FIPS 205), formerly SPHINCS+. Digital signatures that rely only on hash functions. Bigger and slower, but on a different foundation.</li></ul><p>The lattice problem is easy to state. You get a set of linear equations with a small random error added to each one, and you have to recover the secret. Without the errors it is Gaussian elimination. With them, nobody knows an efficient way to do it. ML-KEM and ML-DSA use a structured version of the problem, where plain numbers are replaced by polynomials. The structure is what keeps keys small and operations fast.</p><p>Where it shows up in practice:</p><ul><li>Key exchange in TLS and SSH. Hybrid schemes like X25519MLKEM768 combine a classical exchange with ML-KEM, so the session stays secure as long as one of the two holds. Major browsers and CDNs already ship this, and recent OpenSSH versions use a hybrid post-quantum exchange by default.</li><li>Signatures: certificates, code signing, firmware, tokens. This part of the migration is slower, because the signatures are larger and PKI changes slowly.</li><li>Data at rest with long retention: backups, archives, anything encrypted under a key that was wrapped with RSA.</li></ul><p>In financial systems the list gets long fast: FIX sessions over TLS, mTLS between services, HSM-backed signing, client authentication, and records that regulation requires you to keep for years.</p><h3>Reading the Anthropic result correctly</h3><p>Back to this week. The coverage ranged from alarm to shrugs. The accurate reading sits in between.</p><p><strong>What was found.</strong> A quantum algorithm that solves some of the structured lattice problems behind ML-KEM and ML-DSA asymptotically faster than any previously known method. It needs a quantum computer. According to IBM Research’s analysis, Anthropic reports no improvement for classical attacks, and none for quantum attacks on unstructured lattices.</p><p><strong>What it doesn’t do.</strong> It doesn’t threaten deployed systems. The advantage appears only at key sizes far beyond the real ones. At real sizes the method is much slower than attacks that already exist. IBM’s write-up puts a number on it: even around 2¹⁰⁰⁰ quantum operations would fall well short of what the attack needs against the lowest security levels of both standards. Anthropic tried to extend the technique into a practical attack and could not.</p><p><strong>What changes.</strong> Confidence. The structure that makes these schemes efficient is now something a quantum algorithm can exploit, even if only at absurd sizes. Anthropic’s own wording is that the result lowers its long-term confidence in structured lattices, while it still regards ML-KEM and ML-DSA as two of the strongest public key algorithms available.</p><p>It also matters who found it. An AI model did a meaningful part of the work. In July, Anthropic had already reported a Claude-assisted attack on HAWK, a lattice signature candidate in NIST’s additional signature process. Cryptanalysis is getting faster, and assumptions will be tested more often than before.</p><p>The response from the industry went in one direction. In the same week, companies including Microsoft, Anthropic and Cloudflare publicly urged organizations to move to the NIST post-quantum standards and to speed up the migration.</p><p>So this is no reason to wait. RSA and elliptic curves are still the schemes a quantum computer breaks with far fewer resources. Move now, and make sure you can move again.</p><h3>What to do now</h3><p>None of this advice is new. In April, Meta’s security engineering team published the framework it uses for its own migration, and it reads well next to this week’s news.</p><p>Each system gets a maturity level, from PQ-Unaware up to PQ-Enabled. The question stops being whether the company “has PQC” and becomes where each system sits on that ladder. Priority goes first to anything exposed to offline attacks, which means key exchange and public key encryption, because that is the traffic someone can record today. Signatures come after. Symmetric cryptography with weak parameters comes last.</p><p>Meta also prefers hybrid deployment over straight replacement, so an attacker has to break both the classical and the post-quantum algorithm. And it keeps HQC, a code-based scheme built on different math, as a fallback in case weaknesses show up in lattices. That fallback was described seven months before Anthropic’s papers.</p><p>Here is a shorter version of the same plan, for teams that are not Meta:</p><ol><li><strong>Inventory.</strong> Find where public key cryptography lives in your systems: TLS termination, service mesh, SSH, VPN, signing keys, HSMs, libraries pinned years ago. Most teams don’t have this list.</li><li><strong>Turn on hybrid key exchange where the stack already supports it.</strong> Recent versions of OpenSSL, Go, BoringSSL and the main CDNs do. It protects recorded traffic today, and the classical half covers you if the lattice half ever fails.</li><li><strong>Prioritize by data lifetime.</strong> Anything that must stay confidential for many years goes first. Short-lived session data can wait.</li><li><strong>Build for crypto agility.</strong> The algorithm should be configuration, not code. This week’s result is the best argument for it: the standard you adopt now may not be the last one.</li><li><strong>Diversify long-lived signatures.</strong> For firmware and root keys that have to hold for decades, a hash-based scheme like SLH-DSA rests on a different foundation than lattices.</li><li><strong>Follow the cryptanalysis, not the headlines.</strong> Pick the highest security level your application supports and avoid rushed changes.</li></ol><p>A qubit is two amplitudes and a few rotations. That is enough to catch a spy on a line, and at scale it is enough to retire the cryptography most systems still run on. The migration is an engineering project, and it is easier to start before there is a deadline.</p><h3>References</h3><ul><li>Anthropic, statement on the lattice cryptography papers (Nov 30, 2026): <a href="https://x.com/AnthropicAI/status/2127538548119339339">x.com/AnthropicAI/status/2127538548119339339</a></li><li>Anthropic, the four papers: <a href="https://github.com/anthropics/formal-math/tree/main/lattices">github.com/anthropics/formal-math/tree/main/lattices</a></li><li>IBM Research, “What Anthropic’s new research means for the security of post-quantum cryptography”: <a href="https://research.ibm.com/blog/anthropic-pqc-security">research.ibm.com/blog/anthropic-pqc-security</a></li><li>Nextgov/FCW, “Anthropic research raises questions about security of post-quantum encryption”: <a href="https://www.nextgov.com/cybersecurity/2026/12/anthropic-research-raises-questions-about-security-post-quantum-encryption/417476/">nextgov.com</a></li><li>CNBC, “Tech giants urge post-quantum encryption after NSA cybersecurity warning”: <a href="https://www.cnbc.com/2026/12/03/tech-microsoft-anthropic-quantum-crypto-nsa-warning.html">cnbc.com</a></li><li>Anthropic, “Discovering cryptographic weaknesses with Claude” (HAWK and AES): <a href="https://www.anthropic.com/research/discovering-cryptographic-weaknesses">anthropic.com/research/discovering-cryptographic-weaknesses</a></li><li>NIST FIPS 203, 204 and 205 (August 2024): <a href="https://csrc.nist.gov/projects/post-quantum-cryptography">csrc.nist.gov/projects/post-quantum-cryptography</a></li><li>C. Gidney, “How to factor 2048 bit RSA integers with less than a million noisy qubits” (2025): <a href="https://arxiv.org/abs/2505.15917">arxiv.org/abs/2505.15917</a></li><li>E. Johnston, N. Harrigan, M. Gimeno-Segovia, <em>Programming Quantum Computers</em>, O’Reilly, 2019</li><li>C. Hughes, J. Isaacson, A. Perry, R. Sun, J. Turner, <em>Quantum Computing for the Quantum Curious</em>, Springer, 2021 (open access)</li><li>Meta Engineering, “Post-Quantum Cryptography Migration at Meta: Framework, Lessons, and Takeaways” (Apr 16, 2026): <a href="https://engineering.fb.com/2026/04/16/security/post-quantum-cryptography-migration-at-meta-framework-lessons-and-takeaways/">engineering.fb.com</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d09dc2c20f0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[13 mil candidaturas, 3 vagas, 3 containers]]></title>
            <link>https://medium.com/@rafa.souza.pinto/13-mil-candidaturas-3-vagas-3-containers-e2ca0e2b0643?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2ca0e2b0643</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hrtech]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 19:37:45 GMT</pubDate>
            <atom:updated>2026-09-23T19:37:45.903Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>O que a gente aprendeu sobre arquitetura e time to fill quando a Bonde recebeu 6.185 candidatos numa única vaga no Hubble.</strong></p><p>Passei anos liderando times de engenharia em empresas grandes. Em todo esse tempo, uma das partes mais difíceis do trabalho foi a mesma: abrir uma vaga e achar a pessoa certa pra ela. Não por falta de candidato. O mercado tem gente boa. O difícil é identificar essa pessoa no meio de centenas de currículos, com atenção, sem que isso vire um segundo trabalho pra quem lidera o time. E enquanto a vaga fica aberta, o time absorve a carga e o roadmap espera.</p><p>Esse problema tem nome: time to fill. Foi ele que me fez sair de uma empresa grande pra tocar o Hubble. Eu queria ver até onde tecnologia consegue reduzir esse tempo, não só pro meu time, mas pra qualquer liderança que passa pelo mesmo. Este texto é sobre um caso concreto e sobre a arquitetura que sustenta ele.</p><h3>O caso</h3><p>A <a href="https://bonde.org/">Bonde</a> abriu três vagas na plataforma. Nenhuma delas era de tecnologia. Conteúdo audiovisual, design e suporte à comunidade.</p><p>O resultado em candidaturas:</p><ul><li>Analista de Suporte e Experiência da Comunidade: 6.185 candidaturas</li><li>Designer Pleno: 4.498 candidaturas</li><li>Coordenador(a) de Conteúdo Audiovisual: 2.604 candidaturas</li></ul><p>Mais de 13 mil candidaturas pra três posições. Uma empresa que precisa contratar três pessoas.</p><h3>O que a arquitetura precisa aguentar</h3><p>Uma vaga com 6 mil candidaturas não é problema de banco. É problema de gente. Ninguém lê 6 mil currículos. Se a plataforma só armazena e lista, o recrutador vai olhar os primeiros 50 e contratar dali. O time to fill não melhora, só muda de lugar.</p><p>Então o requisito real é: cada candidatura precisa ser analisada, comparada com a vaga e ranqueada antes de o recrutador abrir a tela. E isso tem que acontecer de forma assíncrona, porque candidatura chega em rajada (divulgação em rede social, indicação, final de semana) e o recrutador não pode esperar.</p><h3>A stack</h3><p>Hoje o Hubble roda com o mínimo que a AWS oferece pra isso:</p><ul><li>Postgres no RDS como fonte única de verdade</li><li>Tasks no ECS pra plataforma (API, cadastro de candidato, recebimento de candidatura, painel do recrutador)</li><li>Task no ECS dedicada à análise de CV</li><li>Uma fila entre a candidatura e a análise</li><li>S3 pros arquivos</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sGVj6jzEc7ZxDiKKIE8W9A.png" /><figcaption>Caminho de uma candidatura no Hubble</figcaption></figure><p>O fluxo: candidato aplica, a plataforma persiste e enfileira. O worker de análise consome a fila, extrai o conteúdo do currículo, roda os modelos de matching contra a descrição da vaga e grava a análise. Quando o recrutador abre a vaga, o ranking já está pronto. Nada acontece na hora da requisição além de ler o resultado.</p><p>Modelos próprios fazem o matching. Bedrock e Voyage AI entram como auxiliares em etapas específicas.</p><p>Essa infra atende a Bonde e os outros clientes com um custo mensal que cabe no orçamento de qualquer startup early stage. O número exato importa menos do que o fato de que ele não cresceu junto com as 13 mil candidaturas.</p><p>Os números que importam são os de tempo. Durante a rajada de candidaturas, a plataforma respondeu com pico de 500ms. Entre a candidatura entrar e a análise do currículo estar pronta pro recrutador, menos de 1 minuto no p99. Na prática, quando o recrutador abre a vaga, tudo que chegou já foi analisado.</p><h3>O que a gente não fez, de propósito</h3><p>Não tem Kubernetes. Não tem microserviço por domínio. Não tem banco vetorial separado. Não tem cache distribuído.</p><p>Depois de anos consolidando plataforma em escala grande, o aprendizado que trouxe é que complexidade de infra precisa ser justificada por carga real, não por carga imaginada. A fila desacopla o pico da análise. O Postgres aguenta 13 mil candidaturas sem suar. Uma task de análise processa a fila em tempo aceitável. Quando um desses três pontos virar gargalo, a gente escala aquele ponto. Até lá, cada real de infra vai pra modelo e pra produto.</p><h3>O que isso muda pro time do cliente</h3><p>O time da Bonde não triou 6.185 currículos. Abriu a vaga, viu os candidatos que o modelo colocou no topo, com a justificativa de por que cada um estava ali, e conversou com essas pessoas. A decisão continua humana. A IA reduz o conjunto de 6 mil pra um número que uma pessoa consegue avaliar com atenção.</p><p>Pra uma liderança de tecnologia, o efeito prático é esse: vaga aberta deixa de ser um projeto paralelo de leitura de currículo. Nos clientes onde medimos, o time-to-fill caiu 60%.</p><h3>Por que estou contando isso</h3><p>Porque passei anos do outro lado. Sei quanto custa um time desfalcado por três meses e sei que a maioria das ferramentas resolve o cadastro, não a decisão. O Hubble nasceu pra resolver a decisão.</p><p>Se você lidera um time de tecnologia e tem vaga aberta há mais tempo do que gostaria, me chama. Quero ouvir como é o seu processo hoje.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2ca0e2b0643" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classical vs Quantum Computing: A Hands-On Experiment with Real Market Data]]></title>
            <link>https://medium.com/@rafa.souza.pinto/classical-vs-quantum-computing-a-hands-on-experiment-with-real-market-data-485130d86c80?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/485130d86c80</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 15:34:05 GMT</pubDate>
            <atom:updated>2026-07-18T18:18:19.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZHD4zwlAehP8ZX6O.jpg" /></figure><p>Pricing agro derivatives with PennyLane and 15 years of soy, corn and FX history; here the quadratic advantage actually shows up, and what I had to fix in my own benchmark to see it.</p><p>I’ve spent most of my career building trading infrastructure for the Brazilian market. Low latency, co-location, the works. When you’ve watched enough “revolutionary” technologies come and go, you develop a reflex: ignore the press release, run the code.</p><p>So that’s what I did with quantum computing.</p><p>The question I wanted answered was narrow on purpose. Not “will quantum change finance” — that’s a panel discussion question, not an engineering one. Mine was: for the specific problem of pricing an option via Monte Carlo, at what point does Quantum Amplitude Estimation actually beat the classical approach, using real market data and honest accounting?</p><p>Turns out I got the answer wrong on the first try. More on that later, because the mistake is the best part.</p><p>Everything runs on a free Colab instance. Notebook is public: <a href="https://github.com/souuzaa/quantum-backtest-sample"><strong>github.com/souuzaa/quantum-backtest-sample</strong></a>.</p><h3>Where I started</h3><p>Two resources carried me from zero to writing circuits.</p><p>The book was <a href="https://a.co/d/015jwrIP">Quantum Computing for the Quantum Curious</a> (Springer, open access, free). It assumes high-school math and still manages to explain superposition and entanglement without lying to you. Rare combination.</p><p>Then the <a href="https://skillbuilder.aws/">AWS Braket training</a> on Skill Builder, mostly to understand how people structure real quantum workloads: local simulator first, managed simulator next, actual QPU only when you’ve proven the circuit deserves the money.</p><p>For code, <a href="https://pennylane.ai/">PennyLane</a>. If you’ve touched PyTorch, the API will feel familiar within an hour.</p><h3>One gate, one lesson</h3><p>A classical bit is 0 or 1. A qubit, before measurement, is a probability amplitude over both. One Hadamard gate is all it takes to see the difference:</p><pre>import pennylane as qml<br><br>dev = qml.device(&quot;default.qubit&quot;, wires=1)<br><br>@qml.qnode(dev)<br>def superposition_circuit():<br>    qml.Hadamard(wires=0)<br>    return qml.probs(wires=0)<br>print(superposition_circuit())   # [0.5, 0.5]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q8OAHAh-5J8Qa2nlvvQCGA.png" /></figure><p>No gate: 100% chance of reading 0, boring, classical. After the Hadamard: a perfect 50/50 split. My mental model comes from trading — an order resting in a dark pool. Filled or rejected? Genuinely undefined until the matching engine says so.</p><p>Now the detail that actually matters. Apply Hadamard twice and the qubit goes <em>back</em> to where it started. The |1⟩ amplitudes cancel each other out; the |0⟩ amplitudes reinforce. That cancellation is interference, and interference — not superposition — is what every useful quantum algorithm exploits. Superposition is the setup. Interference is the trick.</p><h3>Entanglement, or: 2^n states for the price of n qubits</h3><p>Add a CNOT after the Hadamard:</p><pre>dev2 = qml.device(&quot;default.qubit&quot;, wires=2)<br><br>@qml.qnode(dev2)<br>def bell_state():<br>    qml.Hadamard(wires=0)<br>    qml.CNOT(wires=[0, 1])<br>    return qml.probs(wires=[0, 1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*SyljNDuGiPGWlJCwUBdfAA.png" /></figure><p>You get 50% |00⟩, 50% |11⟩. The mixed states |01⟩ and |10⟩? Probability zero. Impossible. Measure one qubit and you know the other, instantly.</p><p>The reason a finance person should care sits in the exponent. Fifty entangled qubits encode about 10¹⁵ joint states. When your instrument’s value depends on soy prices and FX and weather and producer credit all moving together — which is precisely what makes Brazilian agro paper hard to price — an exponential state space is not a curiosity. It’s the whole game.</p><h3>Quantum circuits you can train</h3><p>A Variational Quantum Circuit is a circuit whose rotation angles are trainable parameters. Weights, basically.</p><pre>@qml.qnode(dev3)<br>def variational_circuit(params):<br>    qml.RX(params[0], wires=0)<br>    qml.RY(params[1], wires=1)<br>    qml.CNOT(wires=[0, 1])<br>    qml.RZ(params[2], wires=0)<br>    qml.RY(params[3], wires=1)<br>    return qml.expval(qml.PauliZ(0) @ qml.PauliZ(1))<br><br>opt = qml.GradientDescentOptimizer(stepsize=0.35)<br>for step in range(60):<br>    params, cost = opt.step_and_cost(variational_circuit, params)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*_xINOwTsRFGN_9MA24ZKCw.png" /></figure><p>The loop reads exactly like classical ML. Forward, loss, gradient, update, repeat. Under the hood the gradient comes from the parameter-shift rule instead of backprop (you evaluate the circuit at shifted angles) but the developer experience is the same. Mine hit the theoretical minimum of −1.0 in about ten steps.</p><p>This architecture is the base layer under QAOA, quantum kernels, quantum neural nets. If any near-term quantum ML lands in production finance, it will look like this.</p><h3>The classical baseline, done properly</h3><p>Cheap trick I refuse to play: benchmarking quantum against a strawman. The classical side gets real data.</p><p>The notebook pulls 15 years of history through yfinance (soybean futures (ZS=F), corn (ZC=F), BRL/USD) builds a continuous front-month series, throws away roll artifacts (daily moves above 12% in absolute value are contract rolls, not markets), and fits GBM parameters by maximum likelihood:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y7oOTZ6BKoGL1dIglw8RKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBww6APckGPUzBisxiGmdw.png" /></figure><p>Five thousand paths, 252 trading days, European calls struck 10% out of the money.</p><p>Does the model hold up out of sample? I ran a walk-forward backtest, two years of training data, 21-day forecast, ~150 rolling windows per asset. Mean absolute percentage error came in between 3% and 6.4% depending on the asset, with bias close to zero everywhere. GBM won’t call direction for you, nothing will, but it produces unbiased distributions. For option pricing that’s the property you actually need.</p><h3>The benchmark, the wrong answer, and the two bugs</h3><p>Classical Monte Carlo error shrinks as O(1/√N). Quantum Amplitude Estimation — Brassard et al. 2002 for the math, Woerner &amp; Egger 2019 for the finance application — shrinks as O(1/N). Quadratic advantage, on paper.</p><p>The idea behind QAE still bends my brain a little. You don’t sample scenarios. You encode the entire payoff distribution into the amplitudes of a quantum state, so that the expected value becomes a rotation angle: E[payoff] = sin²(θ). The answer you want is already sitting in the geometry. The algorithm’s job is reading that angle precisely, and each refinement doubles your resolution instead of adding one more vote to an average.</p><p>So I built the benchmark. Real soy parameters, Black-Scholes as ground truth, and QAE’s error bound simulated per Brassard. First run said: QAE breaks even around ±1% precision, wins about 9× at ±0.1%.</p><p>Nine times. For a quadratic speedup. Something smelled off.</p><p>I dug in, and found two methodology bugs — mine, not PennyLane’s.</p><p><strong>Bug one.</strong> Every point on my convergence curve came from a single random draw. One unlucky draw at N=10,000 inflated the fitted QAE constant by roughly 5×. The fix is boring and mandatory: RMSE over 20 repetitions per point.</p><p><strong>Bug two.</strong> This one’s subtler and it’s the real lesson. I was measuring QAE’s error against the continuous Black-Scholes price. But a 5-qubit circuit discretizes the price distribution into 32 grid points, and that discretization carries a fixed 0.4% bias no amount of oracle calls can remove. My estimator was converging beautifully — to the discretized value — and then hitting that floor. The curve fit read the floor as slow convergence. Once I measured estimation error against what QAE <em>actually estimates</em> (the discretized expectation) and reported the grid bias separately, everything snapped into place.</p><p>How do I know the corrected version is right? The empirical constants matched theory: MC constant 212 vs 221 predicted, QAE constant 922 vs 865. When your benchmark reproduces the closed-form prediction, you can stop arguing with yourself.</p><p>The corrected numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeindXFMH2c-nErX5avDyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QZAVPwv8Z2WMnlNyVoWlJQ.png" /></figure><p>The law is clean: speedup ≈ 49/ε. Demand one extra digit of precision and the classical engine pays 100× more; the quantum one pays 10×.</p><p>Caveats, because a benchmark without caveats is marketing. The QAE here is simulated at its theoretical error bound — today’s hardware can’t run deep amplitude estimation circuits at useful scale, full stop. And I’m counting one oracle call as equal in cost to one classical path, which flatters the quantum side; on real devices an oracle call is a deep circuit. What this measures is the scaling law, not tomorrow’s wall clock. I’d still argue scaling laws are the thing worth measuring. They’re what decide technology races in the end.</p><h3>Why I keep coming back to agro</h3><p>CPRs and CRAs (Brazil’s rural product notes and agribusiness receivables) are close to a worst-case pricing problem. Commodity risk, FX risk, weather, producer credit, all correlated, with the interesting probabilities living in the tails (drought plus default, that kind of joint event). Every extra factor multiplies the paths a classical engine burns, which pushes the precision-per-factor requirement straight into the regime where 49/ε gets large.</p><p>An engine that prices this in near real time instead of an overnight batch isn’t an incremental improvement. It changes what a risk desk can do during the day.</p><h3>Next on the list</h3><p>Braket local simulator with finite shots first — free, and it tells you whether the circuit survives sampling noise before you pay for anything. Then SV1, then maybe a real QPU; IonQ charges around a cent per shot, less than my coffee. I also want error bars on the 49/ε constant itself: preliminary runs across master seeds show roughly ±20% variation, and that belongs in the open, not in a footnote.</p><p>The notebook with every experiment above:</p><p><strong>→ </strong><a href="https://github.com/souuzaa/quantum-backtest-sample"><strong>github.com/souuzaa/quantum-backtest-sample</strong></a></p><p>Fork it. Break it. Tell me what I got wrong. Finding my own bugs is how this article got its best section.</p><p><strong>References</strong></p><ul><li>Hughes, C. et al. (2021). <em>Quantum Computing for the Quantum Curious.</em> Springer (open access).</li><li>Brassard, G., Høyer, P., Mosca, M., Tapp, A. (2002). “Quantum Amplitude Amplification and Estimation.” <em>Contemporary Mathematics</em>, 305.</li><li>Woerner, S., Egger, D. J. (2019). “Quantum risk analysis.” <em>npj Quantum Information</em>, 5(15). arXiv:1806.06893</li><li>Orús, R. et al. (2019). “Quantum computing for finance: Overview and prospects.” arXiv:1807.03890</li><li>Stamatopoulos, N. et al. (2020). “Option Pricing using Quantum Computers.” arXiv:1905.02666</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=485130d86c80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-tuning an LLM for Financial Analysis: Three Attempts, Real Lessons]]></title>
            <link>https://medium.com/@rafa.souza.pinto/fine-tuning-an-llm-for-financial-analysis-three-attempts-real-lessons-c9eec7c3e605?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9eec7c3e605</guid>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 18:30:02 GMT</pubDate>
            <atom:updated>2026-04-03T18:30:02.040Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An honest technical account of adapting Llama 3.1 8B to the finance domain using QLoRA — including one complete failure, two partial successes, and what each run taught me.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OmX22XIgMy-dVBgH8kJn3A.png" /></figure><p>The goal was simple to state: take a general-purpose language model and make it a specialist in financial analysis. Input: questions about EBITDA, DCF, ROE, WACC, balance sheets. Output: accurate, structured answers using correct terminology.</p><p>Simple to state. Harder to execute.</p><p>Three training runs, roughly 18 hours of GPU time, and one bricked model later, here’s what actually happened.</p><h2>The Setup</h2><p><strong>Model:</strong> Llama 3.1 8B Instruct, 4-bit quantized version from Unsloth <strong>Method:</strong> QLoRA — fine-tuning that trains only LoRA adapters on top of a frozen base model <strong>Hardware:</strong> NVIDIA RTX 3060 (12 GB VRAM), AMD Ryzen 7 5700G, 32 GB RAM <strong>Framework:</strong> Unsloth + TRL’s SFTTrainer <strong>Serving:</strong> Ollama</p><p>QLoRA was the obvious choice here. A full fine-tune of an 8B model requires far more VRAM than a 12 GB consumer card can offer. With QLoRA, the base model stays frozen and quantized at 4-bit, and only the small LoRA adapter weights (~42M parameters out of 8B) are trained. Peak VRAM usage stayed around 5.8 GB throughout all runs.</p><h2>The Data</h2><p>Three public HuggingFace datasets were in scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y2RK4AwbIujNcxDnshgIaQ.png" /></figure><p><em>Which</em> datasets to include — and how to filter them — turned out to be one of the most consequential decisions in the project. More on that below.</p><h2>Attempt 1: Complete Failure</h2><h3>Configuration</h3><ul><li>Dataset: finance-alpaca only (intended) — in practice, only 3,187 examples made it to training</li><li>Learning rate: 2e-4</li><li>train_on_responses_only: disabled</li><li>Evaluation language: Portuguese</li></ul><h3>What went wrong</h3><p><strong>1. Silent dataset download failure.</strong> The original code used trust_remote_code=True, a deprecated flag that caused sujet-finance to fail silently — zero records saved. Training ran on just 3,187 English examples from finance-alpaca. The model never had a chance.</p><p><strong>2. Loss computed on the entire sequence.</strong> With train_on_responses_only disabled, the model computed loss on both the instruction and the response tokens. Since instructions dominate the token count, the model optimized for predicting <em>question patterns</em> rather than answers. The training loss looked great (0.67) — because predicting the next word in a question is easy. The behavior was terrible.</p><p><strong>3. Learning rate too high.</strong> 2e-4 with a small dataset pushed the model into catastrophic forgetting. It lost its general capabilities and started producing repetitive, incoherent text.</p><p><strong>4. Language mismatch in evaluation.</strong> Training data was 100% English. I evaluated with Portuguese prompts. Results looked even worse than they were.</p><h3>Result</h3><p>The fine-tuned model generated repetitive, incoherent text regardless of input. Financial term coverage: <strong>0%</strong>. A complete write-off.</p><h2>Attempt 2: Working, But Too Terse</h2><h3>What changed</h3><ul><li>Fixed the trust_remote_code=True issue — sujet-finance now loaded correctly</li><li>Filtered sujet-finance to QA task types only (qa, qa_with_context, qa_conversation) — dropping one-word sentiment answers</li><li><strong>Enabled </strong><strong>train_on_responses_only</strong> — the single most impactful change</li><li>Reduced learning rate from 2e-4 to 5e-5</li><li>Switched evaluation to English</li></ul><h3>Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lq-o2B4WANZBUOMsxTO7CQ.png" /></figure><h3>Training results</h3><ul><li>Duration: <strong>~8h 40min</strong></li><li>Train loss: <strong>1.51</strong> / eval loss: <strong>1.198</strong></li></ul><p>The higher loss compared to Attempt 1 is expected and <em>correct</em>. With train_on_responses_only, the model is only predicting response tokens — which are genuinely hard to predict. A low loss here would actually be suspicious.</p><h3>Evaluation results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*464wBusNmYC2f1nlcgJJ3g.png" /></figure><p>The model was <strong>3.7x faster</strong> and produced coherent, correct answers — zero repetition, zero hallucination. The EBITDA calculation was right. Sentiment classification was right. WACC included the full formula.</p><h3>The problem</h3><p><strong>92 words per response.</strong> That’s a sentence, not an analysis.</p><p>The root cause: fingpt-sentiment contributed thousands of single-word training examples (&quot;Bullish&quot;, &quot;Bearish&quot;, &quot;Neutral&quot;), and MIN_OUTPUT_LEN=15 was permissive enough to let them through. The model internalized the short-answer pattern and applied it everywhere — even to questions that deserved a full explanation.</p><p>The model learned <em>what</em> to say, but not <em>how much</em> to say.</p><h2>Attempt 3: Current</h2><h3>Changes from Attempt 2</h3><p><strong>1. Removed </strong><strong>fingpt-sentiment entirely.</strong> Single-word outputs don&#39;t teach a model to generate analysis — they teach brevity. The signal-to-noise ratio of that dataset, for this use case, was negative.</p><p><strong>2. Raised </strong><strong>MIN_OUTPUT_LEN from 15 to 200 characters (~50 words).</strong> Every training example now has a substantive response. Short answers that slipped through before are gone.</p><h3>Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anQNXtJEsskcLs4pJgG1eg.png" /></figure><p>Going from ~10,700 to ~8,100 examples was intentional. Less data, better quality.</p><h3>Training results</h3><ul><li>Duration: <strong>4h 41min</strong> (nearly half of Attempt 2, smaller dataset)</li><li>Train loss: <strong>1.1198</strong> / eval loss: <strong>1.334</strong></li><li>Peak VRAM: 5.8 GB / 11.6 GB</li></ul><h3>Evaluation — per question breakdown</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyTUAgflNMgFBoUZ4vhQ4Q.png" /></figure><p>*FT = Fine-Tuned</p><h3>Aggregate results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgFO7y1Fw_MDRmBR-34oLA.png" /></figure><h3>What improved</h3><p>The core problem from Attempt 2 is solved. Response length now matches the base model (381 vs 375 words). On analytical questions (DCF, ROE, WACC), the fine-tuned model actually produced <em>longer</em> responses than the base — a sign it learned to elaborate, not just answer.</p><h3>What still needs work</h3><p><strong>Informal tone.</strong> On questions q5 and q6, the model responds with:</p><blockquote>“I think that you are confusing two different things…” “I think that the question is asking for something different…”</blockquote><p>This pattern comes from finance-alpaca, which is sourced from Reddit (r/personalfinance, r/investing). The content is correct. The tone is a knowledgeable Reddit user, not a financial analyst. If you want formal, structured responses, the training data needs to sound formal and structured.</p><p><strong>Term coverage dropped slightly</strong> (21% → 18.8%). Partly a measurement artifact — longer responses dilute the ratio even when usage is correct — but also a real signal worth watching.</p><h2>Three Runs, Side by Side</h2><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nQGvJT7TSBUl0q0k5gFfWQ.png" /></figure><p><em>* Misleadingly low — loss computed over the entire sequence including instructions.</em></p><h2>Five Lessons Worth Keeping</h2><h3>1. train_on_responses_only is not optional</h3><p>It’s the difference between training an assistant and training a model that imitates questions. Without loss masking, the loss drops artificially because predicting instruction tokens is easy — and the model “learns” to reproduce the style of the prompt instead of generating answers. Enable it. Always.</p><h3>2. Data quality beats data quantity</h3><p>Attempt 3 used 24% fewer examples than Attempt 2, achieved better train loss (1.12 vs 1.51), trained in half the time, and produced better responses. Stricter filtering is worth more than volume.</p><h3>3. Your dataset teaches style, not just content</h3><p>The model learns <em>how</em> to respond, not just <em>what</em> to respond. Reddit data produces a Reddit-sounding model. If you want a financial analyst, you need training data written like a financial analyst.</p><h3>4. Automatic metrics have limits</h3><p>Term coverage went down from Attempt 2 to Attempt 3 — but the responses are qualitatively better. A model that uses “weighted average cost of capital” in a coherent paragraph scores lower on a term-matching metric than one that lists “WACC, EBITDA, ROE, DCF” in a bullet list. Human evaluation is irreplaceable.</p><h3>5. Higher loss can mean better training</h3><p>The Attempt 1 model had a loss of 0.67 — looked good, was useless. Attempts 2 and 3 have loss above 1.0 — and they work. With train_on_responses_only, loss measures something genuinely hard: predicting technically correct responses. Don&#39;t optimize the number, optimize the behavior.</p><h2>What’s Next</h2><ul><li><strong>Filter </strong><strong>finance-alpaca by response quality</strong> — remove informal or short examples even if they pass the 200-char filter. Tone matters.</li><li><strong>Add high-quality long-form data</strong> — analyst reports, CFA study materials, technical write-ups. Well-written data teaches register, not just facts.</li><li><strong>Test cross-lingual behavior</strong> — the model was trained on English data exclusively; understanding how it handles other languages would be relevant for non-English use cases.</li><li><strong>Increase LoRA rank to 32</strong> — potentially improves adaptation capacity at the cost of ~20% more VRAM and training time.</li></ul><h2>Stack</h2><ul><li><strong>Fine-tuning:</strong> <a href="https://github.com/unslothai/unsloth">Unsloth</a> + TRL SFTTrainer</li><li><strong>Base model:</strong> unsloth/Meta-Llama-3.1-8B-Instruct-bnb-4bit</li><li><strong>Method:</strong> QLoRA (rank 16, alpha 32, dropout 0, gradient checkpointing)</li><li><strong>Export:</strong> GGUF Q4_K_M via llama.cpp (bundled in Unsloth)</li><li><strong>Serving:</strong> Ollama</li><li><strong>Datasets:</strong> HuggingFace Datasets</li><li><strong>GPU:</strong> NVIDIA RTX 3060 12 GB</li></ul><p>The full pipeline — data download, preparation, fine-tuning, GGUF export, and evaluation — is automated across five Python scripts and runs end-to-end on a single consumer GPU.</p><p>Source: <a href="https://github.com/souuzaa/custom-model">https://github.com/souuzaa/custom-model</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9eec7c3e605" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The full local AI stack for financial anomaly detection — architecture, tradeoffs, and what…]]></title>
            <link>https://medium.com/@rafa.souza.pinto/the-full-local-ai-stack-for-financial-anomaly-detection-architecture-tradeoffs-and-what-9b96fce20672?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b96fce20672</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[financial-data]]></category>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[anomaly-detection]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 21:03:41 GMT</pubDate>
            <atom:updated>2026-03-22T19:47:44.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>The full local AI stack for financial anomaly detection — architecture, tradeoffs, and what actually worked</h3><p><em>An autoencoder, a vector database, and a local LLM on a single GPU server. No cloud. No API costs. Real market data.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9NCiSco9b1Rrf1-XQW5nw.gif" /></figure><p>There’s a moment in every ML project where something unexpected comes back from the model and you’re not sure whether to trust it or panic.</p><p>For me, that moment was asking a local LLM — running entirely on my own hardware, zero cloud — to tell me which NASDAQ tickers were most anomalous right now. It answered immediately: TEAM (54), COIN (45), HOOD (45), DDOG (39). Then I opened Google Finance and saw that Atlassian had dropped from $170 to $73 over six months — a 57% decline.</p><p>The model didn’t know that. It figured it out from the data alone.</p><p>This is the story of how the machine learning behind <strong>Alpha AI</strong> works, what it’s actually detecting, and where it still needs to grow.</p><h3>The core idea: teach the model what normal looks like</h3><p>Most anomaly detection approaches fall into two camps: rule-based thresholds (fragile, need constant tuning) or supervised classifiers (require labeled anomalies, which almost never exist at scale in finance).</p><p>Alpha AI takes a third path: <strong>unsupervised reconstruction-based detection</strong>.</p><p>The logic is simple. Train a model to reconstruct <em>normal</em> market behavior as accurately as possible. When it encounters something it wasn’t trained on — a crash, a volume spike, a momentum breakout — it fails to reconstruct it well. That reconstruction error <em>is</em> the anomaly score.</p><p>No labels needed. The model learns normal, and everything else surfaces itself.</p><h3>The data pipeline</h3><p>Before the model sees anything, five years of daily OHLCV data for 50 top NASDAQ tickers flows through a pipeline: download via yfinance, store in PostgreSQL, slice into 30-day sliding windows, engineer 7 features per day, normalize per ticker. The output is a <strong>210-dimensional feature vector</strong> for every window of every ticker.</p><h3>Why 7 specific features</h3><p>Raw OHLCV data is price-level dependent and noisy. A $500 stock and a $20 stock can’t be compared directly. Derived indicators capture <em>market structure</em>, not price level:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wsytQuU0m_gtCBgOFZf40A.png" /></figure><p>Everything is min-max normalized <em>per ticker</em> — not globally. Normalizing globally would let NVDA’s volatility regime distort INTC’s normal range. Per-ticker normalization means “unusual for this stock,” not “unusual for the market.”</p><h3>The role of synthetic data</h3><p>Real data has almost no labeled anomalies. To give the model ground truth for threshold calibration and validation, the pipeline generates stress scenarios using a GBM model parameterized from real ticker statistics — flash crashes, volume spikes, gap-downs. These are stored separately, tagged as label: anomaly, and mixed in at 20% of the training set.</p><p>The synthetic data doesn’t teach the model what anomalies look like. It teaches the model <em>how wrong it can be</em> when it sees one — which is what calibrates the detection threshold.</p><h3>The machine learning core</h3><h3>Convolutional autoencoder</h3><p>The heart of Alpha AI is a 1D convolutional autoencoder trained with PyTorch, running on an RTX 3060 12GB.</p><pre>class AnomalyAutoencoder(nn.Module):<br>    def __init__(self, input_dim=210, latent_dim=32):<br>        super().__init__()<br>        self.encoder = nn.Sequential(<br>            nn.Conv1d(1, 64, kernel_size=3, padding=1),<br>            nn.ReLU(),<br>            nn.Conv1d(64, 32, kernel_size=3, padding=1),<br>            nn.ReLU(),<br>            nn.Flatten(),<br>            nn.Linear(32 * input_dim, latent_dim)<br>        )<br>        self.decoder = nn.Sequential(<br>            nn.Linear(latent_dim, 32 * input_dim),<br>            nn.Unflatten(1, (32, input_dim)),<br>            nn.ConvTranspose1d(32, 64, kernel_size=3, padding=1),<br>            nn.ReLU(),<br>            nn.ConvTranspose1d(64, 1, kernel_size=3, padding=1)<br>        )<br>    def forward(self, x):<br>        z = self.encoder(x.unsqueeze(1))<br>        return self.decoder(z).squeeze(1)</pre><p>The encoder compresses a 210-dim window into a 32-dim latent vector — the model’s internal representation of “what’s happening in this stock right now.” The decoder tries to reconstruct the original window from that compressed form. Training uses only normal windows and MSE loss:</p><pre>criterion = nn.MSELoss()<br>optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)<br>for epoch in range(50):<br>    for batch in normal_dataloader:<br>        loss = criterion(model(batch), batch)<br>        optimizer.zero_grad()<br>        loss.backward()<br>        optimizer.step()</pre><p>The model learns one thing well: what normal reconstruction error looks like. Everything above a learned threshold becomes a candidate anomaly.</p><h3>The P97 threshold</h3><p>After training, reconstruction error is computed across the full training set. The anomaly threshold is set at the <strong>97th percentile</strong> of those errors — the top 3% of historical reconstruction failures become the floor for flagging.</p><pre>train_errors = []<br>with torch.no_grad():<br>    for batch in train_dataloader:<br>        mse = ((model(batch) - batch) ** 2).mean(dim=1)<br>        train_errors.extend(mse.tolist())<br>threshold = np.percentile(train_errors, 97)</pre><p>This percentile is a design choice, not a ground truth. P95 catches more with more noise. P99 is conservative but misses subtle regime drift. P97 is the starting point — backtesting against real outcomes will refine it in later phases.</p><h3>Embeddings and similarity search</h3><p>Every window is also passed through nomic-embed-text (via Ollama) and stored as a 768-dim vector in Qdrant. When a new anomaly is flagged, the system finds the top-k most historically similar past windows using kNN search.</p><pre>def embed_and_store(features, ticker, date_range, label):<br>    vector = ollama.embeddings(<br>        model=&#39;nomic-embed-text&#39;,<br>        prompt=str(features.tolist())<br>    )[&#39;embedding&#39;]<br>    client.upsert(&#39;alpha_windows&#39;, [PointStruct(<br>        id=generate_id(ticker, date_range),<br>        vector=vector,<br>        payload={&#39;ticker&#39;: ticker, &#39;date_range&#39;: date_range, &#39;label&#39;: label}<br>    )])</pre><p>The model doesn’t just say “anomaly.” It says “this looks like what happened on these specific past dates.” That historical context is what makes the LLM explanation genuinely useful rather than generic.</p><h3>What the model actually detected</h3><p>With the pipeline running, here’s what the system surfaced across several real query sessions. The interface is Open WebUI connected to a local MCP server — natural language in, structured answers out, llama3.1:8b generating the explanations entirely on local GPU.</p><h3>Market pulse: who’s most anomalous right now?</h3><blockquote>“Which tickers are most anomalous right now?”</blockquote><pre>TEAM  — 54 anomalies<br>COIN  — 45 anomalies<br>HOOD  — 45 anomalies<br>DDOG  — 39 anomalies<br>Dominant severity: LOW</pre><p>Four tickers from different sectors, all flagged simultaneously. The model isn’t reacting to a single market event — it’s seeing a cluster of stocks each behaving outside their individual historical norms.</p><h3>TEAM: a real collapse, detected</h3><p>TEAM (Atlassian) opened January 20, 2026 at ~$118 and closed March 20, 2026 at $73.73 — a <strong>−37.5% decline in 60 trading days</strong>. The 6-month chart tells a starker story: −56.79% from ~$170 in September 2025, with the steepest leg down accelerating through February 2026.</p><p>The model’s read on the 60-day window:</p><ul><li>Price range during period: $68.81 — $138.44</li><li>Anomaly count: <strong>54 out of 43 trading days</strong></li><li>Max anomaly score: 0.036925</li><li>Top features: volume z-score, RSI-14 momentum shift, VWAP deviation</li></ul><p>54 anomalies across 43 trading days — the model flagged nearly every session. That isn’t a false positive problem. It’s the correct reading of a stock in a persistent, deep structural breakdown. The autoencoder, trained on TEAM’s historical behavior, had never seen it act this way. Every day looked reconstructible as “a bad day” — but the accumulated divergence kept compounding.</p><p>Severity stayed LOW because individual scores sat near the threshold — this was a slow-moving regime shift, not an acute shock. The model correctly distinguished “sustained drift” from “single explosive event.”</p><blockquote><strong>A note on anomaly counts and sliding windows.</strong> The get_ticker_summary tool reports a raw count of flagged windows, not flagged trading days. Because the pipeline uses a 30-day sliding window with a 1-day step, each trading day appears in up to 30 overlapping windows — so a count of 54 across 43 trading days is architecturally expected, not a detection error. A more useful metric would be &quot;percentage of trading days where at least one containing window was flagged,&quot; which collapses the overlapping windows back to a per-day signal. That normalization is on the roadmap.</blockquote><h3>Volatility comparison: NVDA vs AMD vs INTC</h3><blockquote>“Compare NVDA, AMD and INTC by volatility”</blockquote><pre>NVDA: 60.98% annualized<br>AMD:  43.86%<br>INTC: 10.56%</pre><p>This output matters beyond the numbers. An anomaly flag on NVDA is structurally different from the same flag on INTC — NVDA’s “normal” includes daily moves that would be extraordinary for INTC. A single global P97 threshold treats them identically. This comparison is the kind of output that motivates the next iteration: per-volatility-regime thresholds rather than one static percentile for all tickers.</p><h3>Anomaly accumulation over time</h3><blockquote>“What are the anomaly counts for NVDA, AMD, INTC over different time periods?”</blockquote><pre>1D    5D    30D   60D<br>NVDA      2     5     11    23<br>AMD       3     6     15    31<br>AMD       3     6     15    31<br>INTC      0     1      4    10</pre><p>AMD accumulates anomalies faster than NVDA despite lower volatility — suggesting AMD’s anomalies are more sustained rather than episodic. INTC is consistently quiet, matching its low-volatility profile. The model differentiates market behavior across very different regimes without being told anything about the companies themselves.</p><h3>Per-ticker feature attribution</h3><blockquote>“What specific factors contribute most to anomalies in these tickers?”</blockquote><p>The LLM broke down contributing features per ticker:</p><ul><li><strong>NVDA</strong>: volume z-score (4 anomalies), VWAP deviation &gt;10% (3 anomalies), log-returns &gt;5% single-day (2 anomalies)</li><li><strong>AMD</strong>: price momentum &gt;8% (6 anomalies), volume above P75 (4 anomalies), Bollinger Band width (3 anomalies)</li><li><strong>INTC</strong>: price movement &gt;5% (2 anomalies), volume above P75 (1 anomaly), MACD divergence (1 anomaly)</li></ul><p>Different stocks fail differently. NVDA anomalies are volume-driven — likely institutional activity. AMD anomalies are momentum-driven — price moving faster than history expects. INTC anomalies are rare and mixed. Feature attribution turns a score into a hypothesis about <em>why</em> a window was flagged, which is where the local LLM earns its place in the pipeline.</p><h3>VWAP deviation explained</h3><p>One of the follow-up queries tested the LLM’s explanatory depth:</p><blockquote>“What is the significance of VWAP deviation in contributing to anomalies?”</blockquote><p>The model correctly identified three mechanisms: VWAP deviation as a proxy for price momentum (deviation = divergence from volume-weighted mean), trading volume sensitivity (VWAP is volume-weighted, so high-volume sessions dominate), and market sentiment signal (large deviations suggest aggressive accumulation or distribution). It then correctly tied this back to the NVDA-specific context — large institutional trades or significant news events as the likely driver.</p><p>This is a local 8B model, running on a single RTX 3060, producing output that would be useful in a real analyst workflow.</p><h3>MSFT: the quiet one</h3><blockquote>“Give me a summary of MSFT over the last 90 days”</blockquote><pre>Period: Dec 22, 2025 – Mar 20, 2026 (61 trading days)<br>Price range: $381.87 – $486.91  (avg $431.35)<br>Anomaly count: 0<br>Last anomaly: None</pre><p>Zero anomalies. MSFT moved within a $105 range over 90 days — entirely consistent with its historical behavior. The model said nothing. That silence matters. A well-calibrated anomaly detector that <em>doesn’t</em> fire on a stable, large-cap stock in a normal trading period is doing its job correctly. The contrast between MSFT’s zero and TEAM’s 54 is the clearest validation signal in this set of experiments.</p><h3>The infrastructure</h3><p>Everything runs on a single local server:</p><ul><li><strong>OS:</strong> Ubuntu Server 24.04 LTS</li><li><strong>GPU:</strong> RTX 3060 12GB — training and inference on the same card</li><li><strong>RAM:</strong> 32GB DDR4</li><li><strong>Stack:</strong> Docker Compose · Ollama · Qdrant · PostgreSQL · FastAPI MCP server · Open WebUI</li><li><strong>Access:</strong> Tailscale + Cloudflare Tunnel</li></ul><p>The MCP server exposes 6 tools to Open WebUI — get_ticker_summary, list_anomalies, explain_anomaly, find_similar, compare_tickers, get_market_pulse — which is what powers the natural-language interface in all the examples above. Total hardware cost: under $1,200. API cost: $0.</p><h3>Where the model still needs to grow</h3><p>This is a research prototype, and the production gap is worth being direct about.</p><p><strong>Per-regime adaptive thresholds.</strong> The current global P97 treats NVDA and INTC the same. The next version computes rolling thresholds per ticker based on a trailing 90-day reconstruction error window, so the sensitivity adjusts as volatility regimes shift.</p><p><strong>Anomaly count vs. anomaly severity.</strong> 54 events on TEAM and 0 on MSFT is a meaningful signal. But “54 low-severity drift events” and “5 high-severity acute events” currently look the same in count. A compound score — count × mean magnitude × max severity — would produce more actionable output.</p><p><strong>Backtesting.</strong> The model detects. It doesn’t yet tell you what happened in the 5/10/20 trading days <em>after</em> detection. Building that framework — validating the anomaly signal against real subsequent outcomes — is the step that separates a research signal from a tradeable one.</p><p><strong>Synthetic data quality.</strong> GBM scenarios are statistically plausible but miss real microstructure effects: liquidity gaps, correlated cross-ticker crashes, bid-ask spread widening under stress. Heston stochastic volatility is the next upgrade.</p><p><strong>Data freshness bugs.</strong> One query returned NVDA anomaly dates from “June–August 2002.” That’s clearly a metadata indexing issue, not a modeling error — but it’s a good reminder that data pipeline quality limits model quality at every stage.</p><h3>What’s next</h3><ol><li><strong>Per-regime adaptive thresholds</strong> — rolling P97 per ticker, updated on a 90-day trailing window</li><li><strong>Backtesting framework</strong> — what happened after each historically flagged window?</li><li><strong>Cross-ticker correlation</strong> — detecting market-wide anomaly clusters, not just single-stock events</li><li><strong>Real-time intraday feed</strong> — replace daily batch with streaming OHLCV</li><li><strong>Heston stochastic volatility</strong> — better synthetic data for rare-event calibration</li></ol><h3>Final thought</h3><p>The MSFT result stuck with me more than the TEAM flags. It’s easy to evaluate an anomaly detector by what it catches. It’s harder to evaluate it by what it correctly ignores.</p><p>Alpha AI is catching real structural behavior: TEAM’s 37% decline, NVDA’s volume-driven volatility, AMD’s momentum regime, INTC’s relative calm. And it’s staying quiet on MSFT. That calibration — knowing when to fire and when not to — is the actual ML problem. We’re building toward it.</p><p>The production gap is honest and closeable. The signal is real.</p><p><em>The full stack runs local — no cloud, no vendor lock-in, no API costs. If you’re building something similar or want to talk ML infrastructure, reach out.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b96fce20672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linux vs FreeBSD]]></title>
            <link>https://medium.com/@rafa.souza.pinto/linux-vs-freebsd-bb3778e47c44?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb3778e47c44</guid>
            <category><![CDATA[operation-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[freebsd]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 15:26:27 GMT</pubDate>
            <atom:updated>2026-03-08T17:28:07.362Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Latency, Schedulers &amp; the Hidden OS Cost</strong></p><h3>Opening: The Anomaly You Can’t Explain</h3><p>It was a routine Tuesday at the trading desk when the alert fired. P99 latency had spiked — not catastrophically, but enough to be uncomfortable for an order-routing service in a fintech environment where milliseconds carry real financial weight. The code hadn’t changed. The database hadn’t changed. The infrastructure was the same.</p><p>That’s the moment every performance engineer dreads: you’ve already done the obvious work, and the problem is still there. You’ve tuned your queries, added L1/L2 caching, switched your runtime. The throughput numbers look great in your dashboard — 15,000 req/s where there used to be 1,900 — but your tail latencies are misbehaving in ways that don’t show up in averages.</p><p>At some point, the OS stops being invisible. That’s what this article is about.</p><p><strong>Author’s Note<br></strong><em>The throughput jump from ~1,900 to 15,000+ req/s described here is real — achieved on a Bun.js API through L1/L2 caching and PostgreSQL query optimization in a Brazilian fintech backend (code: </em><a href="https://github.com/souuzaa/bun-sample-test"><em>github.com/souuzaa/bun-sample-test</em></a>)<em>. <br>But even after that win, tail latency tells a different story. This article explores why. All benchmark code is available at </em><a href="https://github.com/souuzaa/os-benchmark"><em>github.com/souuzaa/os-benchmark</em></a><em>.</em></p><h3>Why the OS Is Usually Invisible</h3><p>Most backend engineers interact with the OS through three abstractions: the file system, the network stack, and the process scheduler. In practice, these feel like background noise — you write your Go service, you deploy it to Linux, it runs. The OS is a given.</p><p>But latency lives in the gaps. A context switch takes time. A syscall has overhead. Memory allocation goes through an allocator that has its own lock contention story. When you’re moving 100 requests per second, none of this matters. When you’re pushing 15,000, every microsecond in the OS hot path shows up in your p99.</p><p>This is what makes the Linux vs FreeBSD comparison interesting — not as a tribal debate, but as an engineering lens. <strong>Both kernels make explicit tradeoffs.</strong> Understanding those tradeoffs is what tells you where your latency is actually coming from.</p><h3>The Scheduler Duel: CFS/EEVDF vs ULE</h3><h4>Linux: CFS and its successor EEVDF</h4><p>Linux’s Completely Fair Scheduler (CFS) was designed around one principle: fairness over time. Every process gets a proportional share of CPU time, tracked through a virtual runtime counter. Its replacement, EEVDF (Earliest Eligible Virtual Deadline First), introduced in kernel 6.6 and active by default on Ubuntu 24.04 LTS (kernel 6.8), adds deadline awareness — meaning latency-sensitive tasks can be prioritized more precisely.</p><p>For a high-throughput API handling thousands of concurrent connections, this matters. EEVDF reduces the scheduling jitter that causes p99 spikes, because the kernel can correctly identify which runnable task is most deadline-urgent at any given moment.</p><h4>FreeBSD: ULE</h4><p>FreeBSD’s ULE scheduler takes a different approach, optimizing for interactive responsiveness and NUMA-aware load balancing. It’s excellent at keeping processes close to their CPU caches — which is why FreeBSD historically shows strong results in latency consistency benchmarks for certain workloads.</p><p>The catch: ULE was designed for a different usage pattern. High-concurrency server workloads with thousands of short-lived tasks — exactly what a modern API looks like — can produce more scheduling variance on FreeBSD than on a well-tuned Linux system running EEVDF.</p><h3>The Allocator Layer: Where Memory Becomes Latency</h3><p>One of the least-discussed sources of tail latency is the memory allocator. Every time your service allocates or frees memory, the allocator acquires locks, updates metadata, and potentially triggers kernel interactions. Under load, allocator contention is a real bottleneck.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHxC87m3zvNOWYaPD4_AUQ.png" /></figure><p>Rust programs use the system allocator by default (glibc on Linux, FreeBSD’s jemalloc-derived allocator on BSD). Go has its own allocator entirely. The practical implication: a Rust program optimized on Linux may behave differently on FreeBSD not because of kernel differences, but because of allocator behavior under load.</p><h4>The I/O Story: io_uring vs kqueue</h4><p>This is where Linux decisively wins for modern API workloads. io_uring, introduced in Linux 5.1 and now deeply mature, enables truly asynchronous I/O with near-zero syscall overhead by using shared ring buffers between userspace and kernel. For a high-throughput API handling thousands of concurrent connections, this is not a marginal improvement — it’s architectural.</p><p>Go’s net/http and fasthttp libraries on Linux benefit from io_uring via the runtime’s internal poller. <strong>This is one of the reasons Go benchmarks so well in Linux environments at high concurrency.</strong> On FreeBSD, the equivalent is kqueue — a genuinely excellent async notification mechanism that predates epoll and influenced io_uring’s design — but without the batching and zero-copy submission model that makes io_uring transformative for dense I/O workloads.</p><p><strong>io_uring in context<br></strong><em>At 15,000 req/s, a service on Linux with io_uring is making significantly fewer syscalls per second than the equivalent on FreeBSD with kqueue. Each saved syscall is a saved context switch. At this scale, that compounds into measurable latency differences — especially at p99 and p999.</em></p><h3>Where FreeBSD Genuinely Wins</h3><p>Intellectual honesty matters here. FreeBSD is not a worse OS — it’s an OS with different tradeoffs optimized for different workloads.</p><ul><li>Network forwarding and firewall workloads: FreeBSD’s pf and netmap give it an edge in packet-forwarding throughput. This is why Netflix runs FreeBSD on its CDN edge nodes.</li><li>Jitter consistency in certain I/O patterns: Some benchmarks show FreeBSD with lower latency variance than Linux for specific storage workloads, particularly with ZFS.</li><li>ZFS integration: ZFS is a first-class citizen on FreeBSD. ARC memory management and prefetching are more deeply tuned.</li><li>Syscall overhead in specific profiles: FreeBSD’s syscall table has slightly lower overhead for certain patterns — though this gap has narrowed significantly with Linux’s optimizations.</li></ul><h3>Practical Takeaway: What to Measure Before You Care</h3><p>Before switching your OS or tuning kernel parameters, measure what’s actually happening. Here’s the decision tree I’d apply to a fintech API:</p><ol><li>Profile your allocator first.</li><li>Instrument your I/O path — are you syscall-bound or compute-bound?</li><li>Look at your scheduler wake-up latency — perf sched latency on Linux gives you this directly.</li><li>Check your p99 vs p50 gap — if it’s large, jitter is your enemy, not throughput.</li><li>Only then compare OS-level behavior.</li></ol><p>For most fintech backends running Go or Rust on AWS — the answer is Linux, particularly for I/O-heavy workloads. The benchmark data shows FreeBSD’s fileio p99 degrading to 69ms at high concurrency versus Linux’s 2ms — a 3,367% gap driven directly by io_uring’s batched I/O model. That said, FreeBSD delivers 44–54% more req/s on syscall-intensive workloads and edges ahead on DB latency at mid and high concurrency. The OS is not the only variable. The workload profile is.</p><p><strong>Reproduce this benchmark<br></strong><em>All code, setup scripts, and wrk2 runner used to generate these results are available at </em><a href="https://github.com/souuzaa/os-benchmark"><em>github.com/souuzaa/os-benchmark</em></a><em> — including the Go API and the full run-benchmark.sh script.</em></p><h3>Execution Plan: AWS EC2 Benchmark</h3><p><em>Linux vs FreeBSD latency comparison using a Go HTTP API as the workload baseline</em></p><h4>Objective</h4><p>Reproduce and quantify the latency differences between Linux (Ubuntu 24.04 LTS) and FreeBSD 14.1 under realistic API load, using a Go HTTP API as the workload. The goal is not a winner — it’s reproducible data that supports the article’s claims.</p><h3>Phase 1: Infrastructure Setup</h3><p><strong>Instance Selection</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9q9fGEpedBWPgScRCqNTeQ.png" /></figure><p>Important: <strong>Use identical c6i instances (Intel Ice Lake). This eliminates CPU microarchitecture variance. Place all instances in the same AZ on a placement group to minimize network jitter.</strong></p><p><strong>Why Go?<br></strong><em>Go has first-class, officially supported builds for both linux/amd64 and freebsd/amd64 — the same binary compiled on either platform. This eliminates runtime-as-variable and lets the OS be the only independent variable in the benchmark. Same application code, same Go version, same GOMAXPROCS setting, different kernel.</em></p><h3>Phase 2: Application Setup</h3><h4>Benchmark API (Go)</h4><p>Three endpoints to isolate different latency profiles — same code compiled and deployed identically on both platforms. Source: <a href="https://github.com/souuzaa/os-benchmark">github.com/souuzaa/os-benchmark</a></p><pre>func main() {<br> cachedPayload, _ = json.Marshal(map[string]string{&quot;status&quot;: &quot;ok&quot;, &quot;source&quot;: &quot;cache&quot;})<br><br> http.HandleFunc(&quot;/&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  if r.URL.Path != &quot;/&quot; {<br>   http.NotFound(w, r)<br>   return<br>  }<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]string{<br>   &quot;name&quot;:    &quot;os-benchmark&quot;,<br>   &quot;message&quot;: &quot;HTTP server for benchmarking OS-level performance: CPU scheduling, memory allocation, and I/O paths.&quot;,<br>   &quot;endpoints&quot;: &quot;/compute, /cached, /db, /fileio, /concurrent, /mem, /syscall, /health&quot;,<br>  })<br> })<br><br> http.HandleFunc(&quot;/health&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]string{&quot;status&quot;: &quot;healthy&quot;})<br> })<br><br> http.HandleFunc(&quot;/compute&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // Pure compute — isolates scheduler behavior<br>  n := 0<br>  for i := 0; i &lt; 10000; i++ {<br>   n += i<br>  }<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]int{&quot;result&quot;: n})<br> })<br><br> http.HandleFunc(&quot;/cached&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // Pre-allocated response — tests allocator + hot path<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  w.Write(cachedPayload)<br> })<br><br> http.HandleFunc(&quot;/db&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // Simulated DB query — tests I/O path via sleep (epoll/kqueue + Go netpoller)<br>  time.Sleep(2 * time.Millisecond)<br>  results := []map[string]interface{}{<br>   {&quot;id&quot;: 1, &quot;name&quot;: &quot;alice&quot;},<br>   {&quot;id&quot;: 2, &quot;name&quot;: &quot;bob&quot;},<br>   {&quot;id&quot;: 3, &quot;name&quot;: &quot;charlie&quot;},<br>  }<br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(results)<br> })<br><br> http.HandleFunc(&quot;/fileio&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // File I/O — tests VFS, page cache, and disk write/read/delete syscalls<br>  tmpDir := os.TempDir()<br>  path := filepath.Join(tmpDir, fmt.Sprintf(&quot;bench_%d.tmp&quot;, time.Now().UnixNano()))<br><br>  data := make([]byte, 4096)<br>  rand.Read(data)<br><br>  if err := os.WriteFile(path, data, 0644); err != nil {<br>   http.Error(w, err.Error(), 500)<br>   return<br>  }<br><br>  readBack, err := os.ReadFile(path)<br>  if err != nil {<br>   http.Error(w, err.Error(), 500)<br>   return<br>  }<br>  os.Remove(path)<br><br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]interface{}{<br>   &quot;wrote&quot;: len(data),<br>   &quot;read&quot;:  len(readBack),<br>  })<br> })<br><br> http.HandleFunc(&quot;/concurrent&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // High concurrency — spawns goroutines that each do a small syscall (time.Now)<br>  // Stresses the scheduler and OS thread management (epoll/kqueue wake-ups)<br>  const numGoroutines = 500<br>  var wg sync.WaitGroup<br>  var ops atomic.Int64<br><br>  wg.Add(numGoroutines)<br>  for i := 0; i &lt; numGoroutines; i++ {<br>   go func() {<br>    defer wg.Done()<br>    time.Now()<br>    ops.Add(1)<br>   }()<br>  }<br>  wg.Wait()<br><br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]interface{}{<br>   &quot;goroutines&quot;: numGoroutines,<br>   &quot;completed&quot;:  ops.Load(),<br>  })<br> })<br><br> http.HandleFunc(&quot;/mem&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // Memory pressure — allocate and release slices to stress mmap/brk and GC<br>  const rounds = 100<br>  const size = 1 &lt;&lt; 20 // 1 MiB per round<br>  total := 0<br><br>  for i := 0; i &lt; rounds; i++ {<br>   buf := make([]byte, size)<br>   buf[0] = byte(i)<br>   buf[size-1] = byte(i)<br>   total += len(buf)<br>  }<br>  runtime.GC()<br><br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]interface{}{<br>   &quot;rounds&quot;:     rounds,<br>   &quot;bytes_each&quot;: size,<br>   &quot;total&quot;:      total,<br>  })<br> })<br><br> http.HandleFunc(&quot;/syscall&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  // Syscall-heavy — rapid getpid-equivalent calls via os.Getpid + cwd lookups<br>  const iterations = 1000<br>  for i := 0; i &lt; iterations; i++ {<br>   os.Getpid()<br>   os.Getwd()<br>  }<br><br>  w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>  json.NewEncoder(w).Encode(map[string]interface{}{<br>   &quot;iterations&quot;:     iterations,<br>   &quot;syscalls_aprox&quot;: iterations * 2,<br>  })<br> })<br><br> log.Println(&quot;Starting os-benchmark server on :3000&quot;)<br> log.Fatal(http.ListenAndServe(&quot;:3000&quot;, nil))<br>}</pre><h3>Phase 3: Load Testing Protocol</h3><h4>Tool: wrk2 (constant-rate load generator)</h4><p>wrk2 is preferred over wrk for latency measurement because it drives a constant request rate — preventing coordinated omission, which is the single biggest methodological flaw in most latency benchmarks. Run from the dedicated load generator instance, never from the API server itself.</p><pre># Install wrk2 on load generator<br>sudo yum install -y gcc make git openssl-devel<br>git clone https://github.com/giltene/wrk2.git &amp;&amp; cd wrk2 &amp;&amp; make<br> <br># Warmup run (critical — cold JIT/cache skews results)<br>./wrk2 -t4 -c100 -d30s -R1000 http://&lt;server-ip&gt;:3000/compute<br> <br># Measurement runs — 3 endpoints × 3 concurrency levels × 2 OSes<br># Low concurrency<br>./wrk2 -t4 -c50  -d60s -R2000  --latency http://&lt;server-ip&gt;:3000/compute  &gt; results/linux_compute_low.txt<br>./wrk2 -t4 -c50  -d60s -R2000  --latency http://&lt;server-ip&gt;:3000/cached   &gt; results/linux_cached_low.txt<br>./wrk2 -t4 -c50  -d60s -R2000  --latency http://&lt;server-ip&gt;:3000/db       &gt; results/linux_db_low.txt<br> <br># High concurrency<br>./wrk2 -t8 -c500 -d60s -R10000 --latency http://&lt;server-ip&gt;:3000/compute  &gt; results/linux_compute_high.txt<br>./wrk2 -t8 -c500 -d60s -R10000 --latency http://&lt;server-ip&gt;:3000/cached   &gt; results/linux_cached_high.txt<br>./wrk2 -t8 -c500 -d60s -R10000 --latency http://&lt;server-ip&gt;:3000/db       &gt; results/linux_db_high.txt</pre><p><strong>Metrics to Capture (per run)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkvfPawtia_QIDnYwJw1yA.png" /></figure><h3>Phase 4: OS-Level Profiling</h3><h4>Linux — perf &amp; eBPF</h4><pre># Install perf and eBPF tools (Ubuntu 24.04)<br>apt install -y linux-tools-common linux-tools-$(uname -r) bpftrace<br> <br># Scheduler latency histogram (run during load test)<br>perf sched record -a -- sleep 30<br>perf sched latency | head -30<br> <br># Syscall frequency breakdown<br>perf stat -e &#39;syscalls:sys_enter_*&#39; -a sleep 10 2&gt;&amp;1 | sort -k1 -rn | head -20<br> <br># io_uring activity<br>cat /proc/sys/kernel/io_uring_disabled  # Should be 0<br>bpftrace -e &#39;tracepoint:io_uring:* { @[probe] = count(); } interval:s:5 { print(@); clear(@); }&#39;</pre><p><strong>FreeBSD — DTrace</strong></p><pre># Scheduler latency (DTrace)<br>dtrace -n &#39;sched:::off-cpu { self-&gt;ts = timestamp; }<br>           sched:::on-cpu  { @lat[execname] = quantize(timestamp - self-&gt;ts); }&#39; -c &#39;sleep 30&#39;<br> <br># Syscall frequency<br>dtrace -n &#39;syscall:::entry { @[probefunc] = count(); } END { trunc(@, 20); }&#39; -c &#39;sleep 10&#39;<br> <br># kqueue activity<br>dtrace -n &#39;fbt::kqueue_scan:entry { @calls[execname] = count(); }&#39; -c &#39;sleep 10&#39;</pre><h3>Phase 5: Benchmark Results</h3><p>All tests run from the dedicated c6i.2xlarge load generator using wrk2 with constant-rate load. Three concurrency profiles: low (c=50, R=2000 req/s), mid (c=200, R=5000 req/s), high (c=500, R=10000 req/s).</p><p><strong>Low Concurrency (c=50, R=2,000 req/s)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*auM5RGteqmHcr-TI_cV1eg.png" /></figure><p><strong>Mid Concurrency (c=200, R=5,000 req/s)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nx6BS6fHmrAYeZpqZRIORg.png" /></figure><p><strong>High Concurrency (c=500, R=10,000 req/s)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DqP1_BErLK2pRNASF4KcCA.png" /></figure><h4>Overall Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7eL4FGKbkOdGBmgHBCIaw.png" /></figure><h3>Phase 6: Results Analysis</h3><p>The data tells a more nuanced story than a simple winner. Here are the four narratives worth highlighting in the article:</p><h4>1. fileio at high concurrency — Linux’s decisive win</h4><p>The most dramatic finding: FreeBSD’s fileio p99 explodes to 69.69ms at high concurrency versus Linux’s 2.01ms — a 3,367% difference. This is the io_uring effect in practice. Under sustained high I/O load, Linux’s batched submission model keeps tail latency flat while FreeBSD’s kqueue-based path shows severe degradation. For any I/O-heavy API at scale, this is the number that matters most.</p><h4>2. syscall throughput — FreeBSD’s strongest win</h4><p>FreeBSD consistently delivers 44–54% more req/s on the syscall-intensive endpoint across all concurrency profiles, with latency running 7–51% lower than Linux. This aligns with FreeBSD’s historically lower syscall overhead and validates the kqueue design for syscall-dense workloads. If your bottleneck is raw syscall volume rather than I/O batching, FreeBSD has a real edge.</p><h4>3. db at mid and high concurrency — FreeBSD edges ahead</h4><p>Counterintuitively, FreeBSD shows lower db latency at mid (-4.1% p99) and high (-3.4% p99) concurrency. This likely reflects FreeBSD’s memory allocator behavior under PostgreSQL connection pool pressure — jemalloc’s lower fragmentation profile paying off under sustained load.</p><h4>4. compute and cached — Linux wins, margins are small</h4><p>For pure compute and cached response workloads, Linux wins consistently on average latency (7–16%) but the margins at p99 are narrow. At low concurrency, FreeBSD even edges out Linux on compute p99 (-3.6%). These workloads are where OS differences matter least — the bottleneck is the application, not the kernel.</p><p><strong>The headline for the article<br></strong><em>Linux wins for I/O-heavy APIs at high concurrency — the fileio p99 gap alone (2ms vs 70ms) makes it decisive. FreeBSD wins for syscall-dense and memory-intensive workloads. Neither OS is universally faster. The workload profile determines the winner — and now you have the data to prove it.</em></p><h3>Phase 6: Cost &amp; Timeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBDHp06q5prczTUJIih6tg.png" /></figure><p>Tip: Use Spot Instances for the load generator — it doesn’t need persistence. Only the API servers need On-Demand for consistent performance.</p><p><strong>Final Recommendation<br></strong><em>Run the full benchmark in a single 4-hour session. Use a tmux session on each server to keep processes alive. Store all results in S3 immediately — don’t rely on instance storage across reboots. The raw data set, combined with the repo at github.com/souuzaa/os-benchmark, makes the article fully reproducible by any reader.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb3778e47c44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Balancing Speed and Cost: Multi-Zone Transaction Orchestration]]></title>
            <link>https://medium.com/@rafa.souza.pinto/balancing-speed-and-cost-multi-zone-transaction-orchestration-41ddca49fe5b?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/41ddca49fe5b</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Mon, 03 Nov 2025 00:28:59 GMT</pubDate>
            <atom:updated>2025-11-03T00:35:29.230Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbRuE8oPjCGQ37S_kSC-iA.png" /><figcaption>Live Metrics</figcaption></figure><h3>Overview</h3><p>This project explores how to design a <strong>distributed transaction confirmation system</strong> that behaves like a lightweight blockchain proof-of-work network — but optimized for <strong>speed, cost, and observability</strong>.</p><p>Built entirely in <strong>Bun.js</strong>, it combines <strong>micro-services</strong>, <strong>multi-zone orchestration</strong>, and <strong>real-time analytics</strong> to dynamically balance workloads across AWS zones based on <strong>performance and cost</strong>.</p><h3>Architecture at a Glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZWJ9_nS2nion4cp846fCA.png" /><figcaption>Architecture Diagram</figcaption></figure><p>At the core, the system includes three main layers:</p><p><strong>Client Application</strong></p><ul><li>Provides a dashboard to submit transactions.</li><li>Displays live metrics from each AWS zone and the orchestrator.</li><li>Supports different execution modes: auto, cost, performance, and budget.</li></ul><p><strong>Orchestrator</strong></p><ul><li>Acts as the intelligent router.</li><li>Decides whether to send each transaction to <strong>Zone 1 (cheaper, lightweight)</strong> or <strong>Zone 2 (faster, high-performance)</strong>.</li><li>Evaluates cost, latency, and success rate in real time.</li><li>Communicates with a load balancer that directs traffic to the appropriate zone service.</li></ul><p><strong>Application Service (per Zone)</strong></p><ul><li>Each AWS zone hosts a Bun.js service exposing three key endpoints:</li><li><strong>GET</strong> /health → checks availability and latency.</li><li><strong>POST</strong> /confirm → performs hash-based transaction confirmation (simple proof-of-work).</li><li><strong>GET</strong> /analytics → reports throughput, average latency, and success rate.</li></ul><h3>The Proof-of-Work Concept</h3><p>Instead of a complex blockchain mining algorithm, this system uses a <strong>simplified hash validation loop</strong>:</p><p>The worker iterates until a hash with a required prefix (based on “difficulty”) is found.</p><p>Each iteration simulates computational effort — producing measurable latency, cost, and success metrics.</p><h3>Observability &amp; Metrics</h3><p>The orchestrator aggregates metrics every few seconds, exposing:</p><ul><li>Total Requests</li><li>Failure Rate</li><li>Average Turnaround</li><li>Budget Consumption</li><li>Window Reset Timer</li></ul><p>Each zone contributes its own stats:</p><ul><li>Success Rate</li><li>Recent Latency</li><li>Requests Count</li><li>Request Cost</li><li>Confirmations / Failures</li><li>Average Confirmation Time</li></ul><h3>Live Dashboard</h3><p>The front-end dashboard (shown in screenshots) provides a full real-time view:</p><ul><li><strong>Submit Transaction Panel:</strong></li><li>Input a transaction ID, payload, and difficulty.</li><li>Choose between cost, performance, or auto mode.</li><li>Instantly see how the orchestrator decides the best zone.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RK_kQN2JeTTpII4FQV7ttA.png" /><figcaption>Submit Transaction Panel</figcaption></figure><ul><li><strong>Zone Health View:</strong></li><li>Compare throughput and efficiency across zones.</li><li>Zone 1 typically achieves lower cost and ~3–5 ms latency.</li><li>Zone 2 delivers faster hash validation but at higher compute cost.</li><li><strong>Orchestrator Metrics:</strong></li><li>Aggregates system-wide metrics like total requests, remaining budget, and average latency.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fzeTr9M31fB4UuUAsVdJ0A.png" /><figcaption>Zone Health and Orchestrator Metrics</figcaption></figure><h3>Performance Testing</h3><p>Using <strong>Grafana k6</strong>, we ran distributed load simulations against the orchestrator and zones.</p><p><strong>Results Highlights:</strong></p><ul><li>✅ 100 % confirmation success rate</li><li>🕒 Average confirmation duration: <strong>46.78 ms</strong></li><li>⚡ HTTP latency p95: <strong>82 ms</strong></li><li>💰 Zone 1 cost per request: <strong>$1.00</strong></li><li>💰 Zone 2 cost per request: <strong>$5.00</strong></li><li>🧮 &gt; 2,000 successful confirmations with zero failures</li></ul><p>The lightweight design of Bun.js proved ideal for multi-zone deployments — extremely fast startup, low resource footprint, and effortless scalability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sImixMuKIBWq5RO3p44ewg.png" /></figure><h3>Lessons Learned</h3><ol><li><strong>Dynamic orchestration beats static load balancing</strong> — decisions based on real metrics drastically improve efficiency.</li><li><strong>Bun.js</strong> offers outstanding performance for microservices where startup time and throughput matter.</li><li><strong>Observability is part of architecture</strong> — embedding analytics endpoints simplified debugging and performance tuning.</li><li><strong>Cost-aware computation</strong> can be modeled effectively even in simulated proof-of-work systems.</li></ol><h3>Final Thoughts</h3><p>This project demonstrates how <strong>engineering simplicity</strong>, <strong>cost-aware orchestration</strong>, and <strong>modern runtimes like Bun.js </strong>can deliver blockchain-inspired reliability without blockchain complexity.</p><p>It’s a practical blueprint for any distributed backend that needs to make <strong>smart, autonomous decisions across zones</strong> — balancing <strong>performance, budget, and reliability</strong> in real time.</p><p><a href="https://github.com/souuzaa/api-orchestration">Source Code</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ddca49fe5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Which serialization protocol should be used?]]></title>
            <link>https://medium.com/@rafa.souza.pinto/which-serialization-protocol-should-be-used-db57a6fd8b4d?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/db57a6fd8b4d</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[serialization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[messagepack]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Tue, 28 Nov 2023 22:29:40 GMT</pubDate>
            <atom:updated>2023-12-04T11:26:14.908Z</atom:updated>
            <content:encoded><![CDATA[<p>Serialization protocols are essential for transferring data between different systems or applications. They define a standardized way to convert complex data structures into a format that can be easily transmitted and reconstructed. One commonly used serialization protocol is JSON (JavaScript Object Notation), which provides a lightweight and human-readable format for data exchange. Another popular option is Protocol Buffers, which is known for its efficient binary encoding and language-agnostic nature. Ultimately, the choice of serialization protocol depends on factors such as system requirements, performance considerations, and compatibility with existing technologies. It is really important to define which protocol developers should use into their projects when they aim at performance and standardization.</p><p>Knowing what matters between performance and consistency really defines what option might be the best for the software architecture that is being built.</p><p>Below we have a few examples:</p><h3>JSON</h3><pre>{<br>    &quot;message&quot; : &quot;Hello World&quot;<br>}</pre><h3>Protobuf (encoded)</h3><pre>&lt;0A 0B 48 65 6C 6C 6F 20 57 6F 72 6C 64&gt;00 00 00</pre><h3>MessagePack (encoded)</h3><pre>81 a7 6d 65 73 73 61 67 65 ab 48 65 6c 6c 6f 20 57 6f 72 6c 64</pre><h3>Benchmark</h3><p>Using the right library (<a href="https://github.com/dotnet/BenchmarkDotNet">https://github.com/dotnet/BenchmarkDotNet</a>), it is possible to define important metrics for each protocol, aiming to help developers choose the right alternative.</p><h3>Serialize Benchmark Sample</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jQlhJm6KyO95tLdbjP4OIA.png" /></figure><h3>Deserialize Benchmark Sample</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4cw5XEt0EgzVAq5f5lHMgQ.png" /></figure><h3>Overview</h3><p>Above, it is important to note that a more readable serialization protocol would be preferable to binary ones if a developer does not require near real-time service. A more readable message can help with system integration.</p><p>When developers need a faster way to integrate systems, such as real-time processing, it’s better to use binary options like Protobuf and MessagePack because they take less time to serialize/deserialize and use less memory allocation.</p><h3>Conclusion</h3><p>There are many different types of serialization protocols to be used. As software engineers, we need to analyze which one would fit better into the proposed architecture, aiming for consistency, performance, and reliability.</p><p>Source Code: <a href="https://github.com/souuzaa/SerializationBenchmark">https://github.com/souuzaa/SerializationBenchmark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db57a6fd8b4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling team building to create better products]]></title>
            <link>https://medium.com/@rafa.souza.pinto/scaling-team-building-to-create-better-products-b4e34e0811df?source=rss-77a57203dd3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4e34e0811df</guid>
            <category><![CDATA[agile-methodology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Rafa Souza Pinto]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 18:39:56 GMT</pubDate>
            <atom:updated>2023-04-07T15:36:55.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Living in the innovation era requires managers and teams to be very focused on their work.</p><p>Employees are expected to deliver fast and better-then-ever results, taking business to a next level and creating a new experiences for their customers.</p><p>When we are posed with such a challenge it is vital to understand the process which starts from the development team in order to achieve the desired performance. How do they improve their backlog, get inspired and inspire people to think better?</p><p>In my experience managing software engineers I came across very good ideas from developers which changed the way we face difficulties around product development.</p><p>We agreed then to make same changes in agile principles, creating a better team building.</p><p><strong>Breaking daily rules</strong></p><p>On-line daily meetings should not be restrained to a set period of time. Why do we have to allocate just 15 minutes when good ideas might come up after that time?</p><p>Our daily meetings changed to 45 minutes with everyone talking about their setbacks, helping one another fix tasks and discuss relevant topics.</p><p>Now the team has a better understanding of the tasks and create better discussion about what must be done</p><p><strong>The team meeting that creates products</strong></p><p>How do we come up with better ideas, suggestions and improvements?</p><p>The first step was to create a “Discovery” agenda.</p><p>What does that mean?</p><p>Its a meeting to discuss every ideia, questions and hard decisions.</p><p>Created by developers, for developers and run by developers.</p><p>Here is where the game actually changes.</p><p>With the team working together they use this agenda to create innovation.</p><p>It is a safe environment where everyone contributes with their opinion about every part of the product, helping each other to improve it.</p><p>Taking these steps is really important to deliver better products.</p><p><strong>Conclusion</strong></p><p>Although its hard to change how we work, effective team interaction is still very important for business.</p><p>It doesn’t really matter if you follow all the rules, the real deal here is the opportunity they are given to be heard.</p><p>That creates good products, good engineers and better team building.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4e34e0811df" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>