<?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 Gustavo Saboia on Medium]]></title>
        <description><![CDATA[Stories by Gustavo Saboia on Medium]]></description>
        <link>https://medium.com/@gustavosaboia97?source=rss-f18569a5e0b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oiPS3_O8JyJhj2qn3EfJ_Q.png</url>
            <title>Stories by Gustavo Saboia on Medium</title>
            <link>https://medium.com/@gustavosaboia97?source=rss-f18569a5e0b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:25:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gustavosaboia97/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[When Chunking Becomes a Persistence Trap]]></title>
            <link>https://medium.com/@gustavosaboia97/when-chunking-becomes-a-persistence-trap-6f7ae9dd7d63?source=rss-f18569a5e0b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f7ae9dd7d63</guid>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Gustavo Saboia]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 02:08:07 GMT</pubDate>
            <atom:updated>2026-02-10T02:19:13.850Z</atom:updated>
            <content:encoded><![CDATA[<h4>Embeddings, MongoDB, and Misaligned Boundaries</h4><p>Some architectural mistakes don’t fail loudly. They surface slowly — in rising cloud bills, gradually slower queries, and systems that grow more complex without becoming clearer.</p><p>This is one of those stories: the decision to persist <strong>image representations</strong> in MongoDB for a moderation system that, in hindsight, <strong>never needed them stored at all</strong>.</p><h4>The problem</h4><p>The goal was straightforward: analyze user-uploaded images to determine whether they violated the company&#39;s content policies.</p><p>This wasn’t about detecting exact duplicates or applying simple heuristics. We needed <strong>semantic similarity</strong> — the ability to identify that a new image was conceptually similar to known problematic content, even when the pixel values differed.</p><p>We used <strong>Google Vertex AI</strong>, leveraging pre-trained vision models to produce <strong>vector representations</strong> of images. With those representations, we could compute similarity scores (e.g., cosine similarity) against a corpus of previously flagged images.</p><p>High similarity scores triggered review workflows. Low scores allowed content to pass. The machine learning complexity lived entirely inside a managed service. Our responsibility was orchestration.</p><p><strong>The constraints were typical:</strong></p><ul><li>low latency for synchronous analysis</li><li>ability to absorb burst traffic</li><li>cost efficiency at scale</li></ul><p>We were processing <strong>millions of images per day</strong>, most of them legitimate, with a fraction requiring human review.</p><h4>The architecture that made sense</h4><p><strong><em>The initial design felt clean and well-separated:</em></strong></p><ul><li>A <strong>Cloud Function</strong> preprocessed uploaded images (normalizing size, format, etc.) and stored them in <strong>Google Cloud Storage</strong>, triggering an asynchronous workflow.</li><li>An <strong>Embedding Service</strong> retrieved the preprocessed image, converted it to a <strong>224×224 numerical matrix</strong> (the pixel representation expected by Vertex AI), and persisted this in <strong>MongoDB</strong> along with identifiers and metadata.</li><li>An <strong>Analysis Service</strong> read those representations, computed similarity against known violations, applied business rules (thresholds, category-specific logic), and routed the image to the appropriate outcome: approved, flagged, or sent for human review.</li></ul><p><strong><em>The separation felt right:</em></strong></p><ul><li>One service owned the ML boundary</li><li>Another owned policy logic</li><li>MongoDB provided flexible schemas for evolving metadata</li></ul><p>We deployed it.<br>It worked.</p><h4>The slow creep of consequences</h4><p>Three months later, our MongoDB cluster had <strong>tripled in size</strong>.</p><p><strong>Here’s what we didn’t realize at design time:</strong> this wasn’t a compact embedding vector like the 512-dimensional representations typical in ML pipelines. It was a <strong>224×224 pixel matrix</strong> — essentially the preprocessed image in numerical form.</p><p>At ~200KB per image, we were effectively <strong>storing each image twice</strong>: once as a JPEG in Cloud Storage, once as a BSON array in MongoDB.</p><p><strong>On top of that:</strong></p><ul><li>BSON is not optimized for dense numerical arrays</li><li>documents carried multiple indexes (timestamps, status, identifiers)</li><li>Every write triggers index maintenance and write amplification</li></ul><p><strong>The degradation was subtle:</strong></p><ul><li>queries that used to take ~20ms climbed to 40ms, then 60ms</li><li>Replica synchronization lagged under peak load</li><li>The immediate response was horizontal scaling (sharding)</li></ul><p>Performance improved.<br> So did the bill.</p><p>When we audited <strong>access patterns</strong>, the issue became clear:<br><strong>Most of these representations were read exactly once</strong>, during initial analysis.</p><ul><li>Approved images were almost never revisited</li><li>Human reviewers needed the original image, not the representation</li><li>There was no meaningful reuse</li></ul><p>We had built a cache for data that <strong>did not behave like cached data</strong>.</p><h4>The real issue: misaligned boundaries</h4><p>The problem wasn’t the model or the representation itself. It was the confusion between <strong>execution chunking</strong> and <strong>persistence boundaries</strong>.</p><p>Chunking — splitting work into independently executable units — is a fundamental pattern in distributed systems. The Embedding Service followed this well: one image in, one representation out, a clear and retryable execution unit.</p><p>The mistake was turning that execution chunk into a <strong>persistent artifact</strong>.</p><p>Each pipeline stage produced a durable state in MongoDB. Two services coordinated through a shared database, writing and reading data <strong>without a clear understanding of its lifecycle</strong>.</p><p><strong>The representations were <em>derived from data</em>:</strong></p><ul><li>computable from the source image</li><li>lacking independent business meaning</li><li>used only as an intermediate step</li></ul><p>Yet we treated them as first-class entities — replicated, indexed, backed up, and retained.</p><p>This is a classic access-pattern mismatch.</p><p><strong>MongoDB excels when working with documents:</strong></p><ul><li>are updated over time</li><li>queried across multiple dimensions</li><li>require flexible schemas</li></ul><p><strong>Here, the data was:</strong></p><ul><li>written once</li><li>read once</li><li>never updated</li></ul><p>We chose a general-purpose database for what was, in effect, a <strong>transient execution state</strong>.</p><h3>Microservices coupled in practice</h3><p>The two-service architecture made the problem worse.</p><p><strong>In theory, the separation made sense:</strong></p><ul><li>independent scalability</li><li>clear responsibilities</li></ul><p><strong>In practice:</strong></p><ul><li>The Analysis Service had no value without the Embedding Service</li><li>The Embedding Service existed solely to feed the Analysis Service</li><li>They deployed independently but <strong>failed together</strong></li></ul><p>If one slowed down, the other accumulated state.<br>We added network hops, serialization overhead, and operational complexity <strong>without gaining real autonomy</strong>.</p><p>The boundaries existed in diagrams, not in behavior.</p><h3>How I would design it today</h3><p>With hindsight, the solution is much simpler.</p><p><strong>Chunking should be an execution concern, not a data modeling concern.</strong></p><ul><li>Images are stored directly in Cloud Storage</li><li>Each image is identified by a deterministic hash (e.g., SHA-256)</li><li>MongoDB stores only metadata: identifier, context, and moderation status</li><li>Image paths are derived from the hash</li></ul><p><strong>When moderation is triggered:</strong></p><ul><li>A single asynchronous task retrieves the image</li><li>Generates the representation in memory</li><li>Computes similarity</li><li>Applies business rules</li><li>Persists only the final decision</li></ul><p>The representation <strong>never touches the database</strong>.<br>It exists only within the execution pipeline.</p><p>If reprocessing is required — policy changes, new models — the representation is regenerated from the source of truth: the object in storage.</p><p><strong>This design eliminates:</strong></p><ul><li>unnecessary storage costs</li><li>indexing overhead</li><li>coordination between tightly coupled services</li><li>ambiguity around data lifecycle</li></ul><p><strong>And optimizes for:</strong></p><ul><li>cost</li><li>simplicity</li><li>maintainability</li></ul><h3>The lesson</h3><p>Chunking is a powerful tool. But every tool creates seams — and seams create temptation.</p><p>The question is not <em>“can I chunk this?”</em>, but:</p><p><strong>“What is the lifecycle of the data this chunk produces?”</strong></p><ul><li>Transient data → keep it in memory or ephemeral queues</li><li>Derived data → regenerate on demand</li><li>Immutable historical data → use storage optimized for append-only access</li><li>Mutable, queryable data → then a database makes sense</li></ul><p>We treated derived, transient data as if it were core business data.<br>We optimized for a caching pattern that didn’t exist.<br>We drew boundaries aligned with our mental model rather than the actual data flow.</p><p>The system worked. But it cost more, performed worse, and was harder to evolve than it needed to be.</p><h3>Closing thoughts</h3><p>Persistence has a cost — financial and cognitive.</p><p>Every piece of state you store must be backed up, migrated, monitored, and reasoned about during failures. Not every chunk needs to leave a footprint.</p><p>In this case, the image representations solved a problem we didn’t have. Semantic similarity analysis could live entirely in the execution layer, while MongoDB focused on what actually mattered long-term: moderation decisions and metadata.</p><p>Chunking is essential.<br><strong>But restraint is architecture too.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f7ae9dd7d63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java, Python ou Node?]]></title>
            <link>https://medium.com/@gustavosaboia97/java-python-ou-node-ff5b570e5397?source=rss-f18569a5e0b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff5b570e5397</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[comparativa]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programar]]></category>
            <dc:creator><![CDATA[Gustavo Saboia]]></dc:creator>
            <pubDate>Thu, 16 May 2019 04:49:24 GMT</pubDate>
            <atom:updated>2019-05-16T04:49:24.272Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWkL4QRmHnvLiIoXPoU2qA.jpeg" /><figcaption>Desenvolvimento WEB</figcaption></figure><p>Existem diversas linguagens de programação, e todas buscam de forma computacional resolver um determinado tipo de problema, criar inovações ou então criar novos padrões. Porém, minha ideia neste post é basicamente fazer uma pequena reflexão sobre o desenvolvimento com 3 linguagens: Java, Python e Node(Javascript). A ideia não é criar uma luta entre as linguagens, se uma é pior que a outra, ou algo do tipo, mas sim apresentar minha percepção sobre as 3 linguagens e um pouco sobre a experiência de desenvolvimento com cada uma delas.</p><p>Primeiramente, gostaria de dizer que o que for indicado nesse post, foi puramente relacionado a desenvolver uma API REST, ou seja, puramente desenvolvimento voltado a sistemas web. O segundo ponto é que todos os projetos foram iniciados do zero, sem nada que pudesse auxiliar e criar um projeto inicial automaticamente. E terceiro que nem tudo é uma verdade absoluta, ou seja, e neste momento, algo já pode ter sido alterado, e pode mudar a perspectiva sobre determinada tecnologia.</p><p>· JAVA</p><p>Creio que das 3 o Java é linguagem mais madura para web, pois utilizando o Spring, Lombok e outros recursos de bibliotecas, que considero que são o que mantém o Java forte dentro da web, é possível ter uma gama de possibilidades, sendo elas: serialização de objetos, tanto de entradas como de saída, injeção de dependências, forma extremamente fácil de lidar com exceptions, através de Exception Handlers, conexões com banco de dados extremamente simples, como por exemplo o Mongo Repository, que gera o modelo e os métodos para realizar as operações com o banco de dados automaticamente através apenas de uma interface Java, entre outros recursos.</p><p>Entretanto o mundo do Java obviamente não é um mar de rosas, a primeira sensação que considero negativa sobre a linguagem é a verbosidade, programar em Java é verboso, tendo a necessidade de escrita de mais código para fazer as vezes coisas extremamente simples, outro ponto a ser relatado é a necessidade de passar um tempo relativamente alto, para estruturar um projeto simples, contando toda árvore de diretórios, recursos, e geração de pacotes, o que torna o processo de criação de um projeto Java trabalhoso.</p><p>· PYTHON</p><p>A segunda linguagem que tive a experiência web no processo foi o Python, o primeiro bom impacto, é que pra iniciar o projeto é necessário uma quantidade ínfima de configuração, ou seja, o esforço pra gerar o escopo inicial de um projeto é extremamente simples, o que te permite um tempo de desenvolvimento maior, segundo ponto muito interessante é a liberdade que você possui na linguagem, ela não é engessada, possui uma flexibilidade e uma simplicidade na escrita do código saindo do padrão das chaves em estruturas de código, criando e organizando suas estruturas de código através da tabulação, com isso você percebe claramente uma facilidade de organizar, ler, e escrever código, terceiro ponto muito interessante é o gerenciamento das dependências, também possui uma gerência de dependências extremamente simples, através do ‘pip’ que permite o download das dependências a partir de qualquer documento de texto simples.</p><p>O que claramente se percebe no desenvolvimento web com o Python, é que a linguagem ainda não tem tanta maturidade quanto o Java, porém tem uma curva de crescimento relativamente alta, na parte de serialização dos objetos com os modelos, fazendo com que seja necessário trabalhar geralmente com muitos dicionários pra receber e enviar os dados, um segundo ponto que vejo, é o mapeamento dos diretórios do projeto, sendo necessário criar files de inicialização para que determinado diretório seja reconhecido como parte do projeto.</p><p>· Node (Javascript)</p><p>O node foi basicamente a última plataforma que tive a curiosidade desenvolver, e no geral, é uma linguagem simples, talvez por ser muito difundida por todo o mundo usando o Javascript, e por isso traz uma gama de vantagens pra desenvolvimento web, principalmente quando relacionado as respostas da API REST por JSON, por ser simplesmente nativo da linguagem, podendo trabalhar com simplicidade com essa estrutura de dados.</p><p>O que senti de problemas com o Node no geral, foi que para iniciar o projeto existe uma série de configurações para se fazer, no caso de codificar pensando no ES6 e superiores, a gama de configurações e dependências chega a ser chato, configuração de babel e outro para começar a codar acaba atrasando muito o inicio real, um outro problema que vejo, é que a parte de mapeamento do projeto é bem fraca, o que quero dizer com isso? Simples, os imports dentro do node são ruins, necessitando que se passe o caminho completo de cada arquivo, e o que acho pior é, passar esse caminho como String, também sobre os imports, cada vez que tenho um arquivo e quero utilizar o que há declarado nele, também se faz necessário utilizar o famoso “module.exports “ ou “export default” tornando o processo de programar com node mais doloroso.</p><p>Então, essa foi um pouco da experiência que senti, lembrando que apenas a nível de código pra web, porém vale lembrar uma escolha de tecnologia para desenvolvimento vai muito além disso, envolve performance, o que a tecnologia oferece para determinada situação, a arquitetura, o problema que você tem para solucionar entre outros muitos fatores.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff5b570e5397" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>