<?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 Balázs Major on Medium]]></title>
        <description><![CDATA[Stories by Balázs Major on Medium]]></description>
        <link>https://medium.com/@majorbalu?source=rss-a88edd322b5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*D7DOvKQN3XvPEggW</url>
            <title>Stories by Balázs Major on Medium</title>
            <link>https://medium.com/@majorbalu?source=rss-a88edd322b5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:56:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@majorbalu/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[Scaling Real-Time Aggregations Without a Data Platform]]></title>
            <link>https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/scaling-real-time-aggregations-without-a-data-platform-75c2df8e2fdf?source=rss-a88edd322b5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/75c2df8e2fdf</guid>
            <category><![CDATA[data-streaming]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Balázs Major]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 19:45:25 GMT</pubDate>
            <atom:updated>2026-06-02T10:53:29.719Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>We Tried Spark. It Failed. This Is What Actually Worked at 1.5K msg/sec</strong><br><em>A real-world case study on building near real-time aggregations with MongoDB Change Streams</em></p><p>You’re building a real-time system. The scale is significant — 1.5K messages per second pouring in from Kafka. The data is messy: device telemetry from thousands of home devices, each with rhythm of updates. Your requirements seem simple: build near real-time aggregations and let users see device history last 10 hours.</p><p>But your constraints are brutal.</p><p>You have no big data platform. Your primary database is MongoDB, running on three nodes — a master, a slave, and an arbiter. You need to keep the system simple and maintainable.</p><p>This is the story of how we solved it — and how every decision we made came from real failures in production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xQE87Zy0T2KNIlk8owIF1g.png" /><figcaption>Working data lake</figcaption></figure><h3><strong>The Problem</strong></h3><p>Let me set the stage.</p><p>We receive about 1.5K messages per second from Kafka. Each message contains historical device data: signal levels, configuration parameters, operational metrics. We need to:</p><ul><li><strong>Store raw events: </strong>for 10 hours (data lake behaviour).</li><li><strong>Detect patterns: </strong>that take 48 hours to manifest (e.g., “has this home device had critically low signal for the last two days?”).</li><li><strong>Serve aggregated data: </strong>to the UI in near real-time.</li><li><strong>Poor tooling: </strong>on three MongoDB nodes with no separate compute infrastructure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHbBjIo-44OloO1klv92rg.png" /><figcaption>Grafana dashboard (Kafka consumer velocity throughput)</figcaption></figure><p>The throughput requirement alone is challenging. But the real complexity comes from the tension between <strong>raw data retention</strong> and <strong>aggregation accuracy</strong>.</p><h3><strong>Attempt #1: Spark (The Technically Correct Solution)</strong></h3><p>Our first instinct was the data engineer’s go-to: use Spark.</p><p>The architecture made sense:</p><ul><li>Kafka consumer reads events.</li><li>Spark processes and aggregates.</li><li>MongoDB stores results.</li></ul><p>Technically, it was correct. We could express our aggregation logic clearly in SQL. Spark’s distributed nature felt reassuring.</p><p>In production, it was a disaster.</p><p><strong>The problems:</strong></p><ul><li><strong>Operational overhead</strong>: Spark requires careful tuning — memory allocation, executor counts, shuffle partitions. Every configuration choice is a footgun.</li><li><strong>Insufficient resources</strong>: We didn’t have a cluster to run Spark. We tried running it on the on premise cloud infrastructure as the application. This led to resource contention and unpredictable failures.</li><li><strong>No visibility</strong>: We had no metrics, no dashboards. The developers would ask, “Is it working?” and the answer was always guesswork. Logs were cryptic. We couldn’t see what was being aggregated or how far behind we were.</li><li><strong>Instability under load</strong>: When throughput spiked — which was constant — the system would fall behind, fail, and recover in unpredictable ways.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QB4JaBuCIrtfXqqUbxEWXA.png" /><figcaption>Instable data lake</figcaption></figure><p>The real issue: <strong>we had no way to see what was happening</strong>. Without metrics and dashboards, we couldn’t diagnose failures. Every incident became a two-hour investigation.</p><p>We killed the Spark approach after long time.</p><h3><strong>Attempt #2: Scheduled Aggregation Jobs (The Scalability Trap)</strong></h3><p>We pivoted.</p><p>New architecture:</p><ul><li>Kafka → MongoDB (raw <em>satelite</em> collection).</li><li>Scheduled jobs every nth. minute: scan the collection, build aggregations, write results into aggregated collection.</li></ul><p>This felt safer. No Spark. Just <em>MongoDB</em> and <em>Node.js</em>. Simple to understand. Simple to debug.</p><p>For about a week, it worked.</p><p>Then the data volume caught up with us.</p><p><strong>What went wrong:</strong></p><p>The <em>satelite</em> collection was growing at roughly 1.5K inserts per second. A scheduled job running every nth minute would process more than ~100K documents. But each job would:</p><ul><li>Scan the entire collection (or a large subset).</li><li>Group and aggregate in application and with aggregate queries in MongoDB memory.</li><li>Write aggregated results.</li></ul><p>The problem: <strong>aggregation throughput &lt; ingestion throughput</strong>.</p><p>If a job took more minutes to run, the next one would start with minutes of new data already waiting. The queue of unprocessed data grew. By the third job failure or slowdown, the system was hours behind.</p><p>We had <strong>increasing lag</strong>. The aggregations were stale. The system was constantly behind.</p><p>And once again: <strong>no metrics</strong>. We discovered the lag by accident — users complained that the data looked old. We had no dashboard showing the lag growing in real-time.</p><h3><strong>The Hidden Problem: TTL and Data Retention</strong></h3><p>While we were fighting the aggregation problem, another crisis was brewing.</p><p>We were storing raw data in MongoDB using a <strong>TTL (Time To Live) index</strong> for automatic cleanup. The plan was simple: keep data for 24 hours, let MongoDB delete old documents.</p><p>But TTL deletion is not free.</p><p>MongoDB’s TTL process runs every 60 seconds. It scans documents, identifies expired ones, and deletes them. With 1.5K ops inserts per second — roughly <strong>130 million documents per day</strong> — TTL couldn’t keep up.</p><p>Here’s the timeline:</p><ul><li><strong>Target</strong>: 24-hour retention.</li><li><strong>Reality</strong>: After a few days, TTL deletion rate &lt; ingestion rate.</li><li><strong>Result</strong>: The collection grew uncontrollably. Disk usage soared. Query performance tanked.</li></ul><p>The math was simple: <strong>if deletes can’t keep up with inserts, the collection will grow forever</strong>. Once the collection crossed a certain threshold, the system began to degrade — database reads and writes slowed down noticeably, Kafka lag started to grow, and outdated data began piling up faster than we could process it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfiZcl6VH3nHn_PcxE_BDA.png" /><figcaption>Decreasing TTL deletion rate on MongoDB satelite collection with 24 hours TTL</figcaption></figure><p>We had to compromise: try <strong>10-hour retention instead of 24</strong>.</p><p>This solved the operational crisis, but it meant our aggregations couldn’t look back far enough. We were losing historical data we needed.</p><p>The real lesson: <strong>TTL is not a scalable data retention strategy for high-throughput systems</strong>. It’s fine for small collections or cleanup of occasional stale data. But at 1.5K inserts per second, it becomes a bottleneck.</p><h3><strong>The Turning Point: Event-Driven Aggregation</strong></h3><p>In the middle of debugging TTL failures and lag increases, someone asked a simple question:</p><blockquote><em>”Why are we re-scanning the entire collection every minute? We know exactly which documents inserted. MongoDB tells us.”</em></blockquote><p>MongoDB Change Streams.</p><p>Change Streams are a feature that lets you subscribe to <strong>real-time changes</strong> in a collection. When a document is inserted, updated, or deleted, MongoDB publishes a change event. You can process these events as they happen — not in batches, not on a schedule, but <em>in real-time</em>.</p><p>This was the insight that changed everything:</p><p>Instead of:</p><p><em>Kafka → MongoDB → [Scheduled job scans collection] → Aggregations</em></p><p>We could do:</p><p><em>Kafka → MongoDB → [Change Stream: listen for inserts] → Micro-batch → Aggregations &amp; Scheduled jobs for aggregations</em></p><p>This flipped the model from <strong>pull</strong> (scheduled jobs polling) to <strong>push</strong> (events flowing as they arrive).</p><h3><strong>The Final Architecture</strong></h3><p>Here’s what we built:</p><pre>┌─────────┐<br>│  Kafka  │ ~1500-1700 msg/sec<br>└────┬────┘<br>     │<br>     ▼<br>┌─────────────────────────┐<br>│ MongoDB satelite        │ Raw data, ~10h TTL<br>│ (Insert-only stream)    │<br>└────┬────────────────────┘<br>     │<br>     ▼ Change Stream (INSERT events only)<br>┌─────────────────────────┐<br>│ Aggregation Service     │ Node.js<br>│ - Micro-batch buffer    │ Single instance<br>│ - Upsert aggregations   │ Resume token<br>└────┬────────────────────┘<br>     │<br>     ▼<br>┌──────────────────────────────┐<br>│ MongoDB Aggregated Data      │ Time-series style<br>│ - signal-level               │ Vertical growth<br>│ - device (real-time state)   │ Compressible<br>└──────────────────────────────┘<br><br>Additional:<br>┌──────────────────────────────┐<br>│ Scheduled Jobs (Recalc/      │ Every 30min - 2 days<br>│ Backfill)                    │ MongoDB aggregation<br>└──────────────────────────────┘</pre><p>The key ideas:</p><ul><li><strong>Change Streams</strong>: Listen to real-time inserts on <em>satelite</em> collection.</li><li><strong>Micro-batching</strong>: Buffer events for 200–500ms, then process in batches</li><li><strong>Upsert</strong>: Use MongoDB’s atomic increment operator to build aggregations.</li><li><strong>Resume token</strong>: Load and save MongoDB’s change stream position — if the processor crashes, it resumes from where it left off.</li><li><strong>Single instance:</strong> We run a single processor instance to keep the system simple and predictable. In practice, the Change Stream consumer is not horizontally scalable in this setup, since multiple instances would read and process the same events, leading to duplicated aggregation updates. However, with the optimized logic and micro-batching approach, a single instance can handle up to ~6,000 messages per second, making horizontal scaling unnecessary for our current load.</li></ul><h3><strong>How It Works: Change Streams + Micro-Batching</strong></h3><p>When the aggregation service starts, it:</p><ol><li><strong>Loads the resume token</strong> from MongoDB (the last position we processed).</li><li><strong>Opens a Change Stream</strong> on the <em>satelite</em> collection and filters for INSERT events only.</li><li><strong>Buffers incoming events</strong> into memory (200–500ms window).</li><li><strong>Flushes the buffer</strong> either when: it fills up (configurable batch size), or the time window expires (500ms).</li><li><strong>Aggregates the batch</strong> using business logic: extract <em>serial number</em> from each message, calculates <strong>aggregated</strong> <strong><em>real-time or vertical values </em></strong>and generate MongoDB bulk write operations.</li><li><strong>Saves the resume token</strong> so the next restart picks up from here.</li></ol><p>Here’s a simplified example of aggregation of the vertical values:</p><pre>// Input: batch of raw device messages<br>const batch = [<br>  { timestamp: 2026-04-03T15:35:12Z, deviceId: { serialNumber: &#39;DEV001&#39; }, signalLevel: -28 },<br>  { timestamp: 2026-04-03T15:35:14Z, deviceId: { serialNumber: &#39;DEV002&#39; }, signalLevel: -29 },<br>  { timestamp: 2026-04-03T15:36:02Z, deviceId: { serialNumber: &#39;DEV003&#39; }, signalLevel: -25 },<br>];<br><br>// Aggregation logic (pseudocode):<br>// Group by: (serialNumber)<br>// Count low-signal events vertically<br><br>// Output: bulk write operations<br>[<br>  {<br>    updateOne: {<br>      filter: {<br>        serialNumber: &#39;DEV001&#39;,<br>      },<br>      list: {<br>        push: {<br>          timestamp: 2026-04-03T15:35:12Z,<br>          signalLevel: -28,<br>        },<br>      },<br>      upsert: true,<br>    }<br>  },<br>  // ...<br>]</pre><p><em>The aggregated data grows </em><strong><em>vertically</em></strong><em> (more time buckets per device) not </em><strong><em>horizontally</em></strong><em> (exponential document count). This is crucial: it means the aggregated collection size is bounded and compressible.</em></p><h3><strong>Why This Works</strong></h3><p>Let’s talk numbers.</p><p><strong>Ingestion capacity</strong>: Kafka → MongoDB handles 1.5K msg/sec using batch inserts and optimized Kafka configuration. The ingestion layer is horizontally scalable, with multiple Kafka consumers running in parallel by Kafka partitions. Since the data is distributed across 24 partitions, we can fully leverage parallel processing, allowing ingestion throughput to scale predictably as load increases.</p><p><strong>Aggregation capacity</strong>: The Change Stream processor can handle <strong>6K+ ops/sec</strong> in practice. Here’s why:</p><ul><li><strong>Micro-batching</strong> reduces MongoDB round trips (1 write per 200–500 messages, not per message).</li><li><strong>Business logic:</strong> intentionally simple. Aggregations are computed directly from the change document using straightforward calculations, without complex dependencies or cross-entity joins. Bulk operations are limited to simple append-style updates — anything more complex would slow down processing and increase Change Stream lag. And once lag starts to build up, it leads to gaps in the time-series data, breaking the near real-time guarantees of the system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7z4z9BprTkIC6Gtrjp64Q.png" /><figcaption>Incrising Change Stream lag</figcaption></figure><ul><li><strong>Resume token</strong> is tiny (bytes, not documents).</li></ul><p>With capacity of 6K ops/sec and actual throughput of 1.5K–1.7K, we have <strong>3–4x headroom</strong>.</p><p><strong>Memory footprint</strong>: The buffer holds at most 500 documents in memory — negligible.</p><p><strong>Lag</strong>: With 500ms flush windows and sub-second aggregation, the entire pipeline from Kafka to aggregated results takes <strong>1–2 seconds</strong>. True near real-time.</p><h3><strong>Real Production Lessons</strong></h3><h3><strong>1: Metrics and Dashboards Are Non-Negotiable</strong></h3><p>This is the most important lesson from our failures.</p><p>With Spark, we had no visibility. With scheduled jobs, we had no visibility. We only discovered failures when users complained.</p><p>Now, we instrument <strong>everything</strong>:</p><ul><li>Events processed per second.</li><li>Batch sizes and durations.</li><li>Buffer lag and flush frequency.</li><li>MongoDB bulk write latencies.</li><li>Change stream resume token age.</li></ul><p>We use <strong>Prometheus and Grafana</strong>. Every engineer sees:</p><ul><li>Is the Change Stream processor running?</li><li>How far behind is it? (timestamp of last event vs. now)</li><li>What’s the buffer size?</li></ul><p>This changed everything. Incidents that used to take 2 hours to diagnose now take 2 minutes. We see degradation before users do.</p><p><strong>Recommendation</strong>: If you’re building a streaming system, invest in metrics first. It’s worth 10x the development time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QkTkHTcr80cBS1ccbR4ncg.png" /><figcaption>Lag an buffer size in one dashboard</figcaption></figure><h3><strong>2: Operational Simplicity Beats Theoretical Scalability</strong></h3><p>Spark is theoretically more scalable. Scheduled jobs are theoretically simpler to reason about.</p><p>Change Streams + micro-batching wins because:</p><ul><li><strong>Single instance</strong>: No distributed consensus, no rebalancing, no split-brain scenarios.</li><li><strong>Inherent backpressure</strong>: The buffer is bounded; if we get behind, we fill up and that’s visible in metrics.</li><li><strong>MongoDB-native</strong>: No external dependencies, no separate infrastructure.</li><li><strong>Recoverable</strong>: Resume token means we never lose progress; crash and restart picks up where we left off.</li></ul><p>Don’t optimize for 10,000x scale if you need 2–3x capacity. Pick a solution that’s simple to operate <em>today</em>.</p><h3><strong>3: TTL Is Not Data Retention</strong></h3><p>TTL is a background cleanup process. At high throughput, it becomes a bottleneck.</p><p>If you need data retention guarantees, don’t rely on TTL alone. Use:</p><ul><li><strong>Time-based partitioning</strong> (collections per hour/day).</li><li><strong>Explicit archival</strong> (scheduled jobs that move old data).</li><li><strong>Separate TTL indices</strong> (if you must use TTL, isolate it to specific fields).</li></ul><p>In our case, we accepted the constraint: keep data for 10 hours, accept that we lose older data, and build aggregations that are computed before data expires.</p><h3><strong>4: Event-Time vs. Processing-Time Matters</strong></h3><p>Our aggregations use <strong>event-time</strong> (the timestamp when the device measured the value) not <strong>processing-time</strong> (when we received it).</p><p>This is crucial for:</p><ul><li><strong>Correctness</strong>: A delayed message arriving 5 hours late still aggregates into the correct hour bucket.</li><li><strong>Reproducibility</strong>: Re-running aggregations produces the same results.</li><li><strong>Compliance</strong>: For audit/regulatory purposes, event-time is ground truth.</li></ul><p>Processing-time is simpler but fragile. If you care about correctness, use event-time.</p><h3><strong>5: Scheduled Jobs for Recalculation</strong></h3><p>We run scheduled different aggregation jobs every nth. minutes using MongoDB’s aggregation pipeline.</p><p>These jobs:</p><ul><li>Recalculate complex metrics that need historical context.</li><li>Backfill gaps (if the Change Stream processor was down).</li><li>Transform aggregated data for reporting.</li></ul><p>The Change Stream processor handles <strong>velocity</strong>. Scheduled jobs handle <strong>completeness and correctness</strong>.</p><p>Together, they’re resilient.</p><h3><strong>Conclusion</strong></h3><p>We tried the data engineer’s playbook: Spark, scheduled jobs, complex infrastructure. None of it worked.</p><p>What worked was simpler: <strong>event-driven aggregation on MongoDB Change Streams</strong>.</p><p>The real insight wasn’t technical. It was organizational: <strong>invest in visibility and simplicity</strong>. Every complex system we built failed silently until a user complained. Every simple system we built — even when it seemed insufficient — revealed its problems in our metrics before they became crises.</p><p>Your constraints might be different. Maybe you have unlimited infrastructure, a large team, or different throughput requirements. But if you’re in the position we were — needing to do more with less, needing to move fast, needing to understand what’s happening — then the principles apply:</p><ul><li>Make the system observable.</li><li>Keep it simple.</li><li>Use your database’s strengths.</li><li>Accept trade-offs explicitly.</li></ul><p>The system we built handles 1.5K messages per second, maintains near real-time aggregations, and runs on MongoDB nodes.</p><p>And we sleep better knowing we can understand it when it breaks.</p><h3><strong>Further Reading</strong></h3><ul><li><a href="https://docs.mongodb.com/manual/changeStreams/">MongoDB Change Streams Documentation</a></li><li><a href="https://www.oreilly.com/library/view/designing-data-intensive-applications/9781491903063/">Designing Data-Intensive Applications </a>— Chapters on stream processing</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75c2df8e2fdf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/scaling-real-time-aggregations-without-a-data-platform-75c2df8e2fdf">Scaling Real-Time Aggregations Without a Data Platform</a> was originally published in <a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning">Tricks and tips in application development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How a Java Engineer Built a Production Go Logger with AI (and Prevented an Unnecessary Rewrite)]]></title>
            <link>https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/how-a-java-engineer-built-a-production-go-logger-with-ai-and-prevented-an-unnecessary-rewrite-d57d7849ff3a?source=rss-a88edd322b5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d57d7849ff3a</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Balázs Major]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 22:02:55 GMT</pubDate>
            <atom:updated>2026-08-24T15:08:49.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Five months ago, I joined a project as a Java/Kotlin backend engineer. The tech stack: Node (NestJS), Go (GoFr), MongoDB, Flink, Postgres, Kafka.</p><p>My question: In the era of Agentic AI, how does a Java engineer stay relevant when the codebase uses completely different technologies?</p><p>This is how I built a production logging and tracing framework in Go — a language I barely knew — and prevented a costly rewrite.</p><h3><strong>The Heterogeneous Reality</strong></h3><blockquote><em>In distributed systems, observability is not optional — it’s essential.</em></blockquote><blockquote><em>At our company, this meant enforcing strict logging and tracing standards across all services.</em></blockquote><blockquote><em>Every microservice was required to emit structured JSON logs and comply with distributed tracing conventions, such as;</em></blockquote><p>We followed OpenTelemetry tracing standards, including:</p><ul><li><strong>correlationId</strong>: tracks requests across services,</li><li><strong>requestId</strong>: identifies each service call,</li><li><strong>parentRequestId</strong>: links child to parent requests.</li></ul><p>Logging was also standardized across all microservices</p><ul><li>A unified log structure with required fields (e.g., customer and product identifiers)</li><li>Structured communication logging (HTTP / server and client side, Kafka, WebSocket).</li><li>Standardized error handling with stack traces.</li><li>Sensitive data masking.</li></ul><p>Existing implementations already followed these standards:</p><ul><li><strong>Java/Kotlin</strong>: Spring-based with middleware.</li><li><strong>Node.js/NestJS</strong>: Pino-based with interceptors.</li></ul><p>However, the business logic was implemented in Go. These services were responsible for controlling Network Management Systems (NMS), such as switching set-top boxes on and off and managing network devices in real time.</p><p>The problem?<br>There was no Go logging and tracing framework that matched our organization’s standards.</p><p>The proposed solution?<br>Rewrite everything in Java/Kotlin or Node.js?</p><h3><strong>Rewrite or Adapt?</strong></h3><p>The lead developer’s reasoning:</p><ul><li>Java and Node.js are dominant in the org.</li><li>Spring Boot provides battle-tested patterns.</li><li>Developer expertise is in Java or Node.js.</li><li>No Go logging framework = no compliance</li></ul><p><strong>My position: Don’t rewrite working production code.</strong></p><p><strong>Why:</strong></p><ul><li>Go applications were stable, handling production traffic.</li><li>Go has a low resource footprint.</li><li>It’s performance was well-suited NMS operations on OSS environments.</li><li>A rewrite would mean months of development effort and significant risk.</li></ul><p>The real problem wasn’t the system — it was just the logging layer.</p><p>So I looked for an alternative: build a logging framework in Go.</p><p>There was just one catch:<br>I barely knew Go.</p><h3><strong>Designing a Logging and Tracing Framework in Go</strong></h3><p><strong>The Core Architecture</strong></p><p>The corporate logging spec requires single-line JSON to stdout with strict fields: time, logging level, correlationId, requestId, parent requestId, message, communication details, org related structured ids.</p><p>Framework requirements:</p><ul><li>Six log levels (TRACE→FATAL).</li><li>Context-based ID propagation.</li><li>HTTP middleware and client interceptors.</li><li>Kafka logging.</li><li>Sensitive data masking.</li><li>Thread-safe operation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xRHbrn--pfZQQTG38aqEAQ.png" /><figcaption><strong>AI-generated hero</strong></figcaption></figure><h3><strong>Core Logger Implementation</strong></h3><p>Core struct with mutex for thread safety:</p><pre>type UnifiedLogger struct {<br>    loggerName string<br>    config     *Config<br>    writer     io.Writer<br>    counter    int<br>    mu         sync.Mutex<br>}<br><br>type Config struct {<br>    Level          LogLevel<br>    Blacklist      []string<br>    MaxArrayLength int<br>}</pre><p>Environment-driven configuration, functional options pattern for construction:</p><pre>logger := NewUnifiedLogger(<br>  WithLoggerName(&quot;nms-control-service&quot;),<br>  WithConfig(LoadConfigFromEnv()),<br>)<br><br>logger.Info(Fields{Msg: &quot;Device status retrieved&quot;,<br>  CorrelationID: &amp;correlationID,<br>  Params: &amp;Params{ID: &quot;device-12345&quot;, Status: &quot;COMPLETED&quot;},<br>})</pre><h4><strong>Context Propagation</strong></h4><p>Go’s <em>context.Context </em>stores request-scoped tracing IDs:</p><pre>func WithCorrelationID(ctx context.Context, id string) context.Context {<br>  return context.WithValue(ctx, correlationIDKey, id)<br>}<br><br>func GetCorrelationID(ctx context.Context) *string {<br>  if val := ctx.Value(correlationIDKey); val != nil {<br>  if str, ok := val.(string); ok {<br>    return &amp;str<br>}</pre><p>Context-aware logging auto-extracts IDs:</p><pre>func (l *UnifiedLogger) InfoContext(ctx context.Context, fields Fields) {<br>  if fields.CorrelationID == nil {<br>    fields.CorrelationID = GetCorrelationID(ctx)<br>  }<br>  // … extract requestID, parentRequestID<br>  l.log(LevelInfo, fields)<br>}</pre><h4><strong>HTTP Server Middleware</strong></h4><p>Auto-logs HTTP requests/responses:</p><pre>func LoggingMiddleware(config *LoggingConfig) func(http.Handler) http.Handler {<br>  return func(next http.Handler) http.Handler {<br>    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {<br>      // Extract IDs<br>      correlationID := getHeader(r, &quot;x-correlation-id&quot;)<br>      requestID := getHeader(r, &quot;x-request-id&quot;)<br>      // Enrich context<br>      ctx := dpslogger.WithCorrelationID(r.Context(), correlationID)<br>      ctx = dpslogger.WithRequestID(ctx, requestID)<br>      // Log request<br>      logger.InfoContext(ctx, Fields{<br>        Msg: fmt.Sprintf(&quot; → REQUEST %s %s&quot;, r.Method, r.URL.Path),<br>          Communication: buildHTTPComm(r, DirIncoming),<br>      })<br>      // Wrap response writer<br>      rw := &amp;responseWriter{ResponseWriter: w, statusCode: 200}<br>      next.ServeHTTP(rw, r.WithContext(ctx))<br>      // Log response<br>      logger.InfoContext(ctx, Fields{<br>        Msg: fmt.Sprintf(&quot;← RESPONSE %d %s&quot;, rw.statusCode, r.URL.Path),<br>        Communication: buildHTTPComm(r, DirOutgoing, rw.statusCode),<br>      })<br>    })<br>  }<br>}</pre><h4><strong>HTTP Client Interceptor</strong></h4><p><em>RoundTripper</em> wrapper logs outbound calls:</p><pre>type LoggingRoundTripper struct {<br>  Transport http.RoundTripper<br>  Logger *dpslogger.UnifiedLogger<br>}<br><br>func (l *LoggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {<br>  start := time.Now()<br>  // Log request<br>  l.Logger.InfoContext(req.Context(), Fields{<br>  Msg: fmt.Sprintf(&quot; → CLIENT_REQUEST %s %s&quot;, req.Method, req.URL),<br>    Communication: buildHTTPComm(req, DirOutgoing),<br>  })<br>  // Perform request<br>  resp, err := l.Transport.RoundTrip(req)<br>  if err != nil {<br>  l.Logger.ErrorContext(req.Context(), Fields{Msg: &quot;Request failed&quot;, Error: err})<br>    return nil, err<br>  }<br>  // Log response with timing<br>  elapsed := time.Since(start).Milliseconds()<br>  l.Logger.InfoContext(req.Context(), Fields{<br>    Msg: fmt.Sprintf(&quot;← CLIENT_RESPONSE %d&quot;, resp.StatusCode),<br>    Communication: buildHTTPComm(req, DirOutgoing, resp.StatusCode, elapsed),<br>  })<br>return resp, nil<br>}</pre><h4><strong>Kafka Producer Interceptor</strong></h4><p>Wraps <em>segmentio/kafka-go</em> writer:</p><pre>type LoggingKafkaWriter struct {<br>  writer KafkaWriter<br>  logger *dpslogger.UnifiedLogger<br>}<br><br>func (l *LoggingKafkaWriter) WriteMessages(ctx context.Context, msgs …kafka.Message) error {<br>  topic := l.getTopic()<br>  // Log IN_PROGRESS<br>  l.logger.InfoContext(ctx, Fields{<br>    Msg: fmt.Sprintf(&quot;← SEND KAFKA %s&quot;, topic),<br>    Communication: buildKafkaComm(topic, &quot;IN_PROGRESS&quot;),<br>  })<br>  start := time.Now()<br>  err := l.writer.WriteMessages(ctx, msgs…)<br>  elapsed := time.Since(start).Milliseconds()<br>  if err != nil {<br>    l.logger.ErrorContext(ctx, Fields{<br>      Msg: &quot;Kafka write failed&quot;,<br>      Error: err,<br>      Communication: buildKafkaComm(topic, &quot;ERROR&quot;),<br>    })<br>    return err<br>  }<br>  // Log SUCCESS with timing<br>  l.logger.DebugContext(ctx, Fields{<br>    Msg: fmt.Sprintf(&quot;← KAFKA SUCCESS %s (%dms)&quot;, topic, elapsed),<br>    Communication: buildKafkaComm(topic, &quot;SUCCESS&quot;),<br>  })<br>  return nil<br>}</pre><h4><strong>Sensitive Data Masking</strong></h4><p>Recursive masking with circular reference detection:</p><pre>func maskRecursive(obj interface{}, blacklist map[string]bool, depth int) interface{} {<br>  if depth &gt; 15 {<br>    return &quot;[Max depth]&quot;<br>  }<br>  switch v := obj.(type) {<br>  case map[string]interface{}:<br>    result := make(map[string]interface{})<br>    for key, value := range v {<br>      if blacklist[strings.ToLower(key)] {<br>        result[key] = &quot;****&quot;<br>      } else {<br>        result[key] = maskRecursive(value, blacklist, depth+1)<br>      }<br>  }<br>  return result<br>  case []interface{}:<br>    result := make([]interface{}, len(v))<br>    for i, item := range v {<br>      result[i] = maskRecursive(item, blacklist, depth+1)<br>    }<br>  return result<br>  default:<br>    return obj<br>  }<br>}</pre><pre>export LOG_BLACKLIST=&quot;password,secret,apiKey&quot;</pre><h4><strong>Thread Safety</strong></h4><p>Mutex protects counter and writes:</p><pre>func (l *UnifiedLogger) log(level LogLevel, fields Fields) {<br>  l.mu.Lock()<br>  defer l.mu.Unlock()<br>  fields.Params.Counter = l.counter<br>  l.counter++<br>  data, _ := json.Marshal(l.buildOutputFields(level, fields))<br>  l.writer.Write(data)<br>  l.writer.Write([]byte(&quot;\n&quot;))<br>}</pre><h3><strong>AI as a Cross-Stack Multiplier</strong></h3><p>I could not have built this without AI. My Go experience was minimal — I could read code but had never built a production Go system.</p><p>How AI helped:</p><ul><li><strong>Understanding Codebases</strong>: “Explain the middleware pattern in these Go files” → Minutes instead of days.</li><li><strong>Designing Interfaces</strong>: “Design a Go logger matching this spec” → AI suggested functional options pattern, explained why it’s idiomatic.</li><li><strong>Context Propagation</strong>: “Implement context utilities for IDs” → AI caught edge cases: Unexported context keys to prevent collisions, pointer vs. string semantics for optional values, proper nil checking.</li><li><strong>HTTP Middleware</strong>: “Log requests/responses, capture status codes” → AI generated custom <em>responseWriter</em> wrapper with fallback header extraction.</li><li><strong>Kafka Integration</strong>: “Wrap <em>segmentio/kafka-go</em> with logging” → Interface delegation pattern I’d never used.</li><li><strong>Testing</strong>: “Write Go tests for context utils” → Table-driven tests covering edge cases I hadn’t considered.</li></ul><h4><strong>Where Human Judgment Was Critical</strong></h4><p>AI suggests patterns, but can’t decide:</p><ul><li>Architecture: Global logger vs DI? (I chose: both).</li><li>Security: What’s sensitive? How to mask? (API keys: partial, passwords: full).</li><li>Performance: Buffer writes? Pool marshalers? (No — real-time logs, avoid premature optimization).</li><li>Integration: How does this fit our ELK stack? (Validate with production tests).</li></ul><p>AI can’t test production behavior. I had to verify:</p><ul><li>Logs parse correctly in ELK.</li><li>Correlation IDs flow through distributed system.</li><li>No log volume issues.</li></ul><h3><strong>Production Impact</strong></h3><p>Three months in production.</p><p><strong>What Changed:</strong></p><ul><li><strong>Unified Observability</strong>: Single <em>correlationId</em> traces requests across all services independent of different technologies (Java, Node, Go).</li><li><strong>Faster Debugging</strong>: Set-top box not responding?</li></ul><p>Before: Check API logs → orchestration → NMS (manual correlation, 20–30 min).</p><p>After: Search ELK for <em>correlationId</em>, see full flow (2–3 min) with connected services.</p><ul><li><strong>Security Compliance</strong>: Auto-masking passwords, API keys, credentials — required for production.</li><li><strong>Performance Monitoring</strong>: Elapsed time in every log → dashboard metrics, degradation alerts.</li></ul><p><strong>What Didn’t Change:</strong></p><ul><li><strong>Application Logic</strong>: Zero business logic touched.</li><li><strong>Performance</strong>: &lt; 1ms latency, &lt; 0.5% CPU overhead.</li><li><strong>Developer Workflow</strong>: API mirrors Java/Node implementations</li></ul><p><strong>Why the Rewrite Was Dropped:</strong></p><p>Rewrite cost:</p><ul><li>4 months development,</li><li>full re-testing</li><li>high risk in critical systems.</li></ul><p>Logging framework cost:</p><ul><li>2 weeks development (with AI),</li><li>1 week testing,</li><li>minimal risk.</li></ul><p>Result: 5–10% of rewrite cost, same compliance outcome. Go apps stayed in production.</p><h3><strong>Lessons for Backend Engineers in the Agentic AI Era</strong></h3><h4><strong>Language Boundaries Are Permeable</strong></h4><p>I’m a “Java engineer” who shipped production Go code. AI made cross-language work feasible.</p><p>But: Only works if you know fundamentals (HTTP, distributed tracing, concurrency, security). AI translates concepts across languages. It doesn’t teach them.</p><blockquote>Without a solid understanding of the fundamentals, AI doesn’t produce working solutions — it produces boilerplate.</blockquote><h4><strong>AI Amplifies Judgment, Doesn’t Replace It</strong></h4><p>AI excels at: boilerplate, idiomatic patterns, edge cases</p><p>AI fails at: architecture, business constraints, security trade-offs</p><p>Success came from right decisions:</p><ul><li>Don’t rewrite working code</li><li>Prioritize compatibility</li><li>Security is non-negotiable</li><li>Design for observability</li></ul><p>AI implemented them efficiently.</p><h4><strong>“Rewrite vs. Adapt” Is a False Dichotomy</strong></h4><p>Old model: Unknown language? Rewrite in known language.</p><p>With AI: Adapt cost drops from “higher than rewrite” to “medium”</p><p>Targeted adaptation became viable.</p><h4><strong>Focus on Narrow, High-Value Problems</strong></h4><p>Scope: One problem (logging compliance), not entire NMS layer. The existing organisation agreed specification is clear.</p><p>Why it worked:</p><ul><li>Small enough to complete quickly.</li><li>Valuable enough to prevent rewrite..</li><li>Isolated enough to minimize risk.</li></ul><p>AI works best on bounded problems.</p><h4><strong>Production Validation Is Non-Negotiable</strong></h4><p>AI code is probabilistic. Before production:</p><ul><li>Read every line.</li><li>Write comprehensive tests.</li><li>Integration tests on real services.</li><li>Staging deployment + monitoring.</li><li>Validate against ELK schema.</li></ul><p>AI accelerates. Doesn’t eliminate rigor.</p><h4><strong>The Value Is in the Decision, Not the Code</strong></h4><p>2,000 lines, 2 weeks with AI (6–8 weeks without).</p><p>But real value: the decision to build instead of rewrite.</p><p>That decision saved months, avoided high-risk changes.</p><p>AI implemented efficiently. Making the right decision? Still on us.</p><h3><strong>Conclusion</strong></h3><p>Five months ago: How can a Java engineer stay relevant in a heterogeneous stack?</p><p>Answer: Engineering fundamentals + AI to bridge gaps.</p><p>I built a production Go logger (language I barely knew), prevented an unnecessary rewrite. Three months in production, zero issues, unified observability across all services.</p><p>AI was critical. But it didn’t replace judgment or rigor. It amplified them.</p><p>The future isn’t mastering every language. It’s understanding principles deeply enough to apply anywhere — with AI as your translation layer.</p><p>The heterogeneous reality isn’t a problem. It’s an opportunity.</p><h3>References</h3><ul><li>OpenTelemetry standardisastion for logging and tracing / <a href="https://opentelemetry.io/docs/what-is-opentelemetry/">https://opentelemetry.io/docs/what-is-opentelemetry/</a>.</li><li>GO Context / <a href="https://pkg.go.dev/context#Context">https://pkg.go.dev/context#Context</a>.</li><li>Segmentio/kafka-go framework/ <a href="https://github.com/segmentio/kafka-go">https://github.com/segmentio/kafka-go</a></li></ul><p><em>Code examples simplified for clarity. Organization details anonymized.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d57d7849ff3a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/how-a-java-engineer-built-a-production-go-logger-with-ai-and-prevented-an-unnecessary-rewrite-d57d7849ff3a">How a Java Engineer Built a Production Go Logger with AI (and Prevented an Unnecessary Rewrite)</a> was originally published in <a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning">Tricks and tips in application development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Revolutionizing Integration Testing with TestContainers: A Modern Enterprise Approach]]></title>
            <link>https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/revolutionizing-integration-testing-with-testcontainers-a-modern-enterprise-approach-8f27605f720b?source=rss-a88edd322b5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f27605f720b</guid>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[integration-testing]]></category>
            <category><![CDATA[integration-testing-tools]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Balázs Major]]></dc:creator>
            <pubDate>Wed, 31 Dec 2025 16:25:06 GMT</pubDate>
            <atom:updated>2026-06-02T10:54:20.191Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-paced microservices landscape, <strong>integration testing</strong> has become more crucial than ever.</p><p>Unit tests are perfect for validating isolated logic — but they often fail to ensure your service works correctly with <em>real</em> dependencies like databases, message brokers, and schema registries.</p><p>That’s where <a href="https://java.testcontainers.org/"><strong>TestContainers</strong></a> comes in — a modern, code-first approach to integration testing that eliminates the pain of manual environment setup and brittle test infrastructure.</p><h3>The Integration Testing Challenge in Enterprise Systems</h3><p>Modern enterprise applications rarely operate in isolation. They depend on a complex web of systems: message brokers (Kafka, RabbitMQ), databases, schema registries, and third-party APIs.</p><p>Testing these integrations has traditionally been painful, involving:</p><ul><li>Complex local setup with Docker or shared test servers.</li><li>Fragile, environment-dependent test results.</li><li>Long feedback cycles due to manual setup.</li><li>Port conflicts and inconsistent configuration.</li><li>Shared environments that become a bottleneck.</li></ul><p>In short — the testing setup often becomes <em>harder to maintain than the code itself</em>.</p><h3>The Testing Pyramid and Where TestContainers Fits</h3><p><strong>Component and integration testing</strong> sit between unit and full end-to-end tests.</p><p>At this level, you want to test your service <em>in isolation</em>, but using <em>real</em> external systems (not mocks).</p><p>This is precisely where <strong>TestContainers</strong> brings the most value — enabling realistic tests that spin up actual brokers, databases, or registries in lightweight, disposable containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UpTqu60hsA_IF_55sb7O0w.png" /><figcaption>Testing pyramid with TestContainers</figcaption></figure><h3>A Real-World Example: Adapter service</h3><p>In one of our enterprise services — a <strong>Adapter service</strong> — we adopted a TestContainers-based testing strategy to replace our legacy Docker Compose setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e-k4ysBxQ0ZWZQdW1vWkcA.png" /><figcaption>Adapter stream flow</figcaption></figure><h3>Core Stack</h3><ul><li><strong>Spring Boot 3</strong> — <em>Kotlin</em>.</li><li><strong>Spring Cloud Stream</strong> — with dual binders.</li><li><strong>RabbitMQ — </strong>input message broker.</li><li><strong>Kafka — </strong>output message broker.</li><li><strong>Confluent Schema Registry — </strong>with<strong> </strong>Avro schema registry.</li><li><strong>TestContainers — </strong>for low level integration testing.</li></ul><h3>Build &amp; Testing</h3><ul><li><strong>Gradle (Kotlin DSL).</strong></li><li><strong>JUnit 5</strong> + <strong>MockK.</strong></li><li><strong>GitLab CI/CD.</strong></li></ul><p>The service acts as a bridge; it consumes <em>service results</em> from RabbitMQ and publishes <em>status updates</em> to Kafka topics (serialized in Avro schema).</p><h3>The Legacy Way: Docker Compose-Based Dependencies</h3><p>In the past, our tests used <strong>Docker Compose</strong> to orchestrate dependencies:</p><pre># docker-compose.yml<br>version: &#39;3.7&#39;<br>services:<br>  kafka:<br>    image: ${KAFKA_IMAGE}<br>    depends_on:<br>      - zookeeper<br>    ports:<br>      - ${KAFKA_EXT_PORT}:${KAFKA_INT_PORT}<br><br>  schema-registry:<br>    image: ${SCHEMA_REGISTRY_IMAGE}<br>    depends_on:<br>      - kafka<br>    ports:<br>      - ${SCHEMA_REGISTRY_EXT_PORT}:${SCHEMA_REGISTRY_INT_PORT}</pre><p>This worked — but came with serious drawbacks:</p><ul><li>⚠️ External orchestration overhead.</li><li>⚠️ Port conflicts in CI/CD.</li><li>⚠️ Brittle cleanup (containers left running).</li><li>⚠️ Slow startup time.</li><li>⚠️ Separate configuration drift between test and prod.</li></ul><h3>The Modern Way: TestContainers as Infrastructure-as-Code</h3><p>With <strong>TestContainers</strong>, we manage all infrastructure directly from Kotlin code.</p><p>Gradle configuration</p><pre>dependencies {<br>  testImplementation(&quot;org.testcontainers:testcontainers&quot;)<br>  testImplementation(&quot;org.testcontainers:junit-jupiter&quot;)<br>  testImplementation(&quot;org.testcontainers:rabbitmq&quot;)<br>  testImplementation(&quot;org.testcontainers:mongodb&quot;)<br>}<br><br>sourceSets {<br>  create(&quot;integrationTest&quot;) {<br>    kotlin.srcDir(&quot;src/integration-test/kotlin&quot;)<br>    resources.srcDir(&quot;src/integration-test/resources&quot;)<br>    compileClasspath += sourceSets[&quot;main&quot;].output + configurations[&quot;testRuntimeClasspath&quot;]<br>    runtimeClasspath += output + compileClasspath<br>  }<br>}</pre><p>Kafka + Schema Registry Setup with TestContainers</p><pre>abstract class AbstractKafkaWithSchemaRegistryTestContainer {<br>  companion object {<br>    private val network = Network.newNetwork()<br>    private val DOCKER_HOST = if (System.getenv(&quot;CI_PIPELINE_ID&quot;) != null) &quot;docker&quot; else &quot;localhost&quot;<br><br>    @ClassRule<br>    @JvmField<br>    val kafka = FixedHostPortGenericContainer(&quot;confluentinc/cp-kafka:7.5.0&quot;)<br>      .withFixedExposedPort(9092, 9092)<br>      .withEnv(&quot;KAFKA_NODE_ID&quot;, &quot;1&quot;)<br>      .withEnv(&quot;KAFKA_PROCESS_ROLES&quot;, &quot;broker,controller&quot;)<br>      .withNetwork(network)<br>      .waitingFor(Wait.forLogMessage(&quot;.*Transitioning from RECOVERY to RUNNING.*&quot;, 1))<br><br>    @ClassRule<br>    @JvmField<br>    val schemaRegistry = GenericContainer(&quot;confluentinc/cp-schema-registry:7.5.0&quot;)<br>      .withExposedPorts(8081)<br>      .withEnv(&quot;SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS&quot;, &quot;PLAINTEXT://kafka:29092&quot;)<br>      .withNetwork(network)<br>      .waitingFor(Wait.forLogMessage(&quot;.*Cluster ID:.*&quot;, 1))<br><br>    init {<br>      kafka.start()<br>      schemaRegistry.start()<br><br>      val kafkaPort = kafka.getMappedPort(9092)<br>      val schemaPort = schemaRegistry.getMappedPort(8081)<br>      System.setProperty(&quot;KAFKA_BOOTSTRAP_SERVER&quot;, &quot;$DOCKER_HOST:$kafkaPort&quot;)<br>      System.setProperty(&quot;AVRO_REGISTRY_URL&quot;, &quot;http://$DOCKER_HOST:$schemaPort&quot;)<br>    }<br>  }<br>}</pre><p>Full Integration Test Example</p><pre>@SpringBootTest<br>@ActiveProfiles(&quot;cloudstream&quot;)<br>@TestPropertySource(<br>  properties = [<br>    &quot;spring.cloud.stream.kafka.binder.auto-create-topics=true&quot;,<br>    &quot;spring.cloud.stream.kafka.binder.producer-properties.auto.register.schemas=true&quot;<br>  ]<br>)<br>class BaseHappyFlowIntegrationTest : AbstractKafkaWithSchemaRegistryTestContainer() {<br><br>  @Test<br>  fun `should read service activation result and publish to Kafka successfully`() {<br>    // Given<br>    val rabbitResponse = Foo(<br>      name = &quot;create&quot;<br>    )<br><br>    // When<br>    publishToRabbitMQ(rabbitResponse)<br><br>    // Then<br>    verifyKafkaMessage { baz -&gt;<br>      assertEquals(&quot;create&quot;, baz.name)<br>    }<br>  }<br>}</pre><h3>Key Benefits of the TestContainers Approach</h3><ol><li><strong>Infrastructure as Code</strong> — versioned, reviewable, and maintainable.</li><li><strong>Parallel and Isolated Execution</strong> — no shared state or port conflicts.</li><li><strong>Automatic Resource Management</strong> — lifecycle handled automatically.</li><li><strong>CI/CD Friendly</strong> — works seamlessly with any Docker-enabled runner.</li><li><strong>Real Dependencies, Real Confidence</strong> — tests use real brokers and databases.</li><li><strong>Dynamic Port Allocation</strong> — no hardcoded ports, no conflicts.</li><li><strong>Smart Wait Strategies</strong> — fewer flaky tests, faster feedback.</li></ol><h3>Best Practices for Enterprise-Grade TestContainers</h3><h3>1. Singleton Container Reuse</h3><pre>companion object {<br>  @ClassRule<br>  @JvmField<br>  val kafka: GenericContainer&lt;*&gt; = createKafkaContainer().apply { start() }<br>}</pre><h3>2. Shared Network Configuration</h3><pre>private val network = Network.newNetwork()<br>val kafka = GenericContainer(&quot;confluentinc/cp-kafka:7.5.0&quot;)<br>  .withNetwork(network)<br>  .withNetworkAliases(&quot;kafka&quot;)</pre><h3>3. Environment-Aware Hostnames</h3><pre>private val DOCKER_HOST = if (System.getenv(&quot;CI_PIPELINE_ID&quot;) != null) &quot;docker&quot; else &quot;localhost&quot;</pre><h3>4. Reliable Health Checks</h3><pre>.waitingFor(<br>  Wait.forLogMessage(&quot;.*Transitioning from RECOVERY to RUNNING.*&quot;, 1)<br>    .withStartupTimeout(Duration.ofSeconds(60))<br>)</pre><h3>Performance &amp; CI Optimisation</h3><ul><li>Use lightweight images.</li><li>Leverage Docker layer caching in CI.</li><li>Reuse containers across test classes.</li><li>Set appropriate memory limits.</li><li>Run tests in parallel wisely.</li></ul><pre>val integrationTest by tasks.registering(Test::class) {<br>  description = &quot;Runs the integration tests.&quot;<br>  group = &quot;verification&quot;<br>  testClassesDirs = sourceSets[&quot;integrationTest&quot;].output.classesDirs<br>  classpath = sourceSets[&quot;integrationTest&quot;].runtimeClasspath<br>  shouldRunAfter(&quot;test&quot;)<br>  useJUnitPlatform()<br>}</pre><h3>Monitoring and Observability in Tests</h3><h3>Container Health Logs</h3><pre>println(&quot;Kafka network info: ${kafka.containerInfo.networkSettings}&quot;)<br>println(&quot;Schema Registry network info: ${schemaRegistry.containerInfo.networkSettings}&quot;)</pre><h3>Metrics to Track</h3><ul><li>Test execution duration.</li><li>Container startup time.</li><li>Resource utilisation (CPU/memory).</li><li>Test stability and flakiness.</li></ul><h3>Conclusion: The Future of Integration Testing</h3><p><strong>TestContainers</strong> marks a fundamental shift in how enterprise teams handle integration testing.</p><p>By defining infrastructure directly in code, you get:</p><ul><li><strong>Developer Productivity</strong> — fast, consistent local setup.</li><li><strong>CI/CD Reliabilit</strong>y — isolated, reproducible tests.</li><li><strong>Maintainability</strong> — version-controlled test environments.</li><li><strong>Confidence</strong> — real dependencies, realistic results.</li></ul><p>As microservices ecosystems grow, this approach isn’t just convenient — it’s essential.</p><p>TestContainers turns integration testing from a tedious setup chore into a powerful part of your development workflow.</p><p><em>This article is based on a real-world Adapter service built with Spring Boot, Kotlin, and enterprise-grade message processing requirements. The full implementation demonstrates production-ready TestContainers integration in a microservice architecture.</em></p><h3>References</h3><ul><li><a href="https://java.testcontainers.org/">TestContainers Official Documentation</a></li><li><a href="https://spring.io/blog/2023/06/23/improved-testcontainers-support-in-spring-boot-3-1">Spring Boot TestContainers Integration (Spring Blog)</a></li><li><a href="https://www.enterpriseintegrationpatterns.com/">Enterprise Integration Patterns</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f27605f720b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/revolutionizing-integration-testing-with-testcontainers-a-modern-enterprise-approach-8f27605f720b">Revolutionizing Integration Testing with TestContainers: A Modern Enterprise Approach</a> was originally published in <a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning">Tricks and tips in application development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving MongoDB Connection Drop Issues by Tuning TCP Keep-Alive Settings]]></title>
            <link>https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/solving-mongodb-connection-drop-issues-by-tuning-tcp-keep-alive-settings-eb179cab972c?source=rss-a88edd322b5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb179cab972c</guid>
            <dc:creator><![CDATA[Balázs Major]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 19:35:41 GMT</pubDate>
            <atom:updated>2024-09-13T19:35:41.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*xdUYKczdu2hnyJl7HtriFA.jpeg" /></figure><p>When running distributed systems, database connections are essential for smooth operation. But what happens when a seemingly stable system starts encountering sporadic connection drops after a database upgrade? This exact scenario unfolded in our Spring Boot application after we upgraded to <strong><em>MongoDB 6</em></strong> from version <strong><em>4</em></strong> Despite no changes to the application itself, we started seeing mysterious connection drops, leading to errors that only manifested after periods of inactivity.</p><p>In this article, we’ll walk you through our investigation into the problem, including how we uncovered the issue using detailed <strong><em>TRACE-level logging</em></strong> and ultimately resolved it by adjusting the operating system’s <strong><em>TCP keep-alive</em></strong> settings.</p><h3>The Problem: Connection Drops After MongoDB Upgrade</h3><p>Our application was running smoothly on <strong>MongoDB 4</strong>, but after upgrading to <strong>MongoDB 6</strong>, we started experiencing intermittent connection failures. These connection drops were sporadic and didn’t cause immediate system failures but appeared after idle periods, leading to various errors during read operations. The same issues were seen across multiple microservices, regardless of whether they used <strong><em>primary</em></strong> or <strong>secondaryPreferred</strong> read preferences.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fRx8QDhg9AL4AEct4zYNGg.jpeg" /></figure><p>Our Spring Boot applications encountered the following errors:</p><p><strong>Read Exception:</strong></p><pre>com.mongodb.MongoSocketReadException: Exception receiving message<br>...<br>Caused by: java.net.SocketException: Connection reset</pre><p><strong>Write Exception</strong>:</p><pre>com.mongodb.MongoSocketWriteException: Exception sending message<br>...<br>Caused by: io.netty.channel.StacklessClosedChannelException: null</pre><p>These errors only started appearing after the <strong><em>MongoDB upgrade</em></strong>, even though the applications remained unchanged. The connection failures occurred randomly but consistently after idle periods, making them difficult to reproduce on demand.</p><p>Interestingly, we also observed similar errors in the <strong><em>Kubernetes health check</em></strong> logs. The health checks would intermittently fail due to stale connections, but these failures didn’t trigger pod restarts. This was because, by the time the next health check ran, the MongoDB driver had already cleaned up the stale connections, re-establishing healthy ones and allowing the checks to pass.</p><h3>The Investigation: Leveraging TRACE-Level Logging</h3><p>To investigate further, we increased the logging verbosity for both <strong><em>Netty</em></strong> and <strong><em>MongoDB</em></strong> drivers by setting `<em>io.netty.channel</em>` and `<em>com.mongodb</em>` to <strong><em>TRACE</em></strong> level. This allowed us to trace the exact flow of connections and understand why certain connections were failing after periods of inactivity.</p><p>Here’s what we uncovered in the logs.</p><h4>The Example Flow of the Issue</h4><p>The application attempted a read operation on the <strong><em>first secondary node</em></strong> (when using `<em>secondaryPreferred</em>`), but after an idle period, the MongoDB driver threw a `<em>MongoSocketWriteException</em>`, caused by a `<em>StacklessClosedChannelException</em>`, indicating the network had dropped the connection:</p><pre>Handling description changed event for server hostname:27017 with description ServerDescription{address=&lt;masked-hostname-2&gt;:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketWriteException: Exception sending message}, caused by {io.netty.channel.StacklessClosedChannelException}</pre><p>Upon this failure, the MongoDB driver attempted to retry the operation by switching to the <strong>second secondary node</strong>, only to encounter the same issue:</p><pre>Retrying the operation &#39;aggregate&#39; due to the error &quot;com.mongodb.MongoSocketWriteException: Exception sending message&quot;. Attempt number: #2.</pre><p>In services where the <strong>primary</strong> read preference was set, the first connection attempt would fail in a similar manner after idle periods, throwing `<em>MongoSocketWriteException</em>`, but then a retry would succeed using a newly established connection.</p><p>Despite these retries, the connection pool held onto stale connections that had been dropped by the network during idle periods, causing the initial failures.</p><h4>Netty Logs: DNS Resolution and Connection Handling</h4><p>Additionally, <strong><em>Netty logs</em></strong> captured the low-level connection handling and DNS query results, but they didn’t contribute directly to solving the issue.</p><p>While informative, these DNS-related logs didn’t explain the connection drop issues we were facing.</p><h3>Investigating Socket Lifetimes with `netstat`</h3><p>As part of our investigation, we used the <strong><em>netstat</em></strong> command to monitor the state of the sockets behind the database connections. This allowed us to track how long the connections stayed open and how they behaved during idle periods.</p><p>We ran the following <strong>netstat</strong> command on the application server to filter for MongoDB-related connections:</p><pre>netstat -an -p TCP | grep :27017</pre><p>This command lists all active connections to MongoDB (assuming the default port <strong>27017</strong>). Below is an example of the output we observed:</p><pre>tcp 0 0 192.168.xxx.xxx:57303 192.168.xxx.xxx:27017 ESTABLISHED 12345/java<br>tcp 0 0 192.168.xxx.xxx:57304 192.168.xxx.xxx:27017 ESTABLISHED 12345/java<br>tcp 0 0 192.168.xxx.xxx:57305 192.168.xxx.xxx:27017 ESTABLISHED 12345/java<br>tcp 0 0 192.168.xxx.xxx:57306 192.168.xxx.xxx:27017 TIME_WAIT -<br>tcp 0 0 192.168.xxx.xxx:57307 192.168.xxx.xxx:27017 FIN_WAIT1 12345/java</pre><p>The majority of connections were in the <strong>ESTABLISHED</strong> state, actively communicating with the database. However, some connections were found in the <strong>TIME_WAIT</strong> and <strong>FIN_WAIT1</strong> states, indicating they were closing but still being tracked by the system. This hinted at the issue where the firewall would drop idle connections after about 10 minutes, which were then detected by the application only when reused.</p><h3>The Root Cause: TCP Keep-Alive Mismatch</h3><p>After carefully analyzing the logs and ‘netstat’ command results, it became clear that the underlying cause of these connection drops was a mismatch in <strong>TCP keep-alive</strong> settings.</p><p>In <strong>MongoDB 4</strong>, the driver itself configured TCP keep-alive to <strong><em>300 seconds</em></strong>. However, with <strong>MongoDB 6</strong>, the driver now relies on the <strong>operating system’s keep-alive settings</strong>. By default, most Linux distributions have the `<em>net.ipv4.tcp_keepalive_time</em>` set to <strong>7200 seconds</strong> (2 hours), which was too long for our setup.</p><p>Our network firewall was configured to drop idle connections after <strong>10 minutes</strong> of inactivity, meaning connections would be silently terminated after sitting idle for too long. The MongoDB client would not detect this until it attempted to reuse the connection, leading to the `SocketException` and `StacklessClosedChannelException` errors.</p><h4>The Solution: Tuning TCP Keep-Alive Settings</h4><p>The solution was to adjust the OS-level <strong>TCP keep-alive settings</strong> to ensure idle connections were monitored before the firewall dropped them.</p><p>We modified the following parameter:</p><p><strong>TCP Keep-Alive Time</strong>: We reduced the `<em>net.ipv4.tcp_keepalive_time</em>` from the default <strong>7200 seconds</strong> to <strong>300 seconds</strong> (5 minutes). This ensured that the operating system would send keep-alive probes to idle connections more frequently than the firewall’s timeout.</p><p>After making this change, we monitored the applications and found that the intermittent connection drops disappeared. The MongoDB connection pool maintained stable connections even after long periods of inactivity, preventing the driver from attempting to reuse stale, broken connections.</p><h4>Connection Pools and Keep-Alive: Why It Matters</h4><p>Using a <strong>connection pool</strong> improves performance by reusing open connections, avoiding the overhead of establishing new connections for every operation. However, idle connections in the pool can be silently dropped by firewalls or other network components if they remain inactive for too long.</p><p>By tuning the <strong>TCP keep-alive</strong> settings, we ensured the OS actively monitored idle connections and detected when they were no longer valid, allowing it to close them before the application attempted to reuse them.</p><h3>Conclusion</h3><p>In distributed systems, silent connection drops can be difficult to diagnose, especially when they occur after idle periods. In our case, upgrading to <strong>MongoDB 6</strong> triggered these issues because the driver began relying on OS-level keep-alive settings, which didn’t match our firewall’s timeout.</p><p>By reducing the <strong>TCP keep-alive</strong> interval, we prevented idle connections from being dropped silently, eliminating the sporadic errors we had been seeing. If you encounter similar connection drops after upgrading to <strong>MongoDB 6</strong> or newer, reviewing and adjusting your TCP keep-alive settings could resolve the problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb179cab972c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning/solving-mongodb-connection-drop-issues-by-tuning-tcp-keep-alive-settings-eb179cab972c">Solving MongoDB Connection Drop Issues by Tuning TCP Keep-Alive Settings</a> was originally published in <a href="https://medium.com/solving-mongodb-connection-drop-issues-by-tuning">Tricks and tips in application development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>