<?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 İbrahim on Medium]]></title>
        <description><![CDATA[Stories by İbrahim on Medium]]></description>
        <link>https://medium.com/@remidosol8?source=rss-ddedfd1fa7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XZakqIk8CND_kJzMj21_Kg.png</url>
            <title>Stories by İbrahim on Medium</title>
            <link>https://medium.com/@remidosol8?source=rss-ddedfd1fa7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 13:36:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@remidosol8/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 is this thing called a saga? #7: Cloud, CI/CD, and one very long trace]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-7-cloud-ci-cd-and-one-very-long-trace-83d99353424a?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/83d99353424a</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[cdktf]]></category>
            <category><![CDATA[traceability]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 19:20:41 GMT</pubDate>
            <atom:updated>2026-09-18T19:20:41.720Z</atom:updated>
            <content:encoded><![CDATA[<p>The last phase of the series was three things at once: infrastructure as code for GKE, a CI pipeline, and observability. My calendar was not happy. This post is also where I tell you plainly what I did not run, because a series about building things honestly should end honestly.</p><h3>The trace that survived the outbox</h3><p>Let me start with the part I’m most fond of. I switched on OpenTelemetry in all three services (Spring Boot 4 has a starter for it), turned on Kafka observation so producers and consumers create spans and carry the traceparent header, pointed everything at Grafana&#39;s all-in-one otel-lgtm image, and looked at a job&#39;s trace. Every service had spans. And every hop started a <em>new</em> trace.</p><p>Why? Because the outbox poller sends from a scheduled thread, milliseconds or hours after the transaction that wrote the row, with no trace context left in its pockets. Every reliability boundary you add is also a context boundary. The outbox row, the queue, the retry: all of them drop the thread-local context on the floor.</p><p>The fix is a column. The outbox writer stores the current W3C traceparent in the row at write time. The poller restores it around the send, so the Kafka producer span becomes a child of the original request. On the Debezium path, the same column is mapped to a Kafka header by the outbox router. Consumers continue from the header as usual.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gkmfQWx2SZ4j5Ezvk1HXng.png" /><figcaption><strong>The </strong><strong>traceparent rides in the outbox row, so the trace doesn&#39;t break when a different thread sends the event later.</strong></figcaption></figure><p>Result: one trace, 14 spans, across three services and three topics: nine spans in job-service (the HTTP request, the security filter, two consumer spans), two in credit-service, three in llm-worker, including the Redis evalsha of the token bucket from <a href="https://medium.com/p/ea2d0b09060a">Part 5</a>. And it worked in CDC mode too, which was the real test, because Debezium&#39;s header came from the column and not from any Java code. Every log line carries [service, traceId, spanId, jobId], so in Grafana you grep a job id in Loki and jump to the trace in Tempo.</p><p>Two rule-four moments hid in this feature. First, Boot’s test annotation for tracing enables the tracer but not the propagator unless export is enabled, so my test injected nothing until I set export on and the exporter off. Second, changing the Debezium router’s field placement while the WAL still held rows without the new column made the connector task fail with “not a valid field name”. The order matters: run the migration, let the connector drain the old rows with the old placement, <em>then</em> change the placement. That went straight into the runbook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEDMCc0GZLM_d45ZK01aJA.png" /><figcaption><strong><em>Fourteen spans, one story. The thread is the trace id; it survives the mailbox and the conveyor belt because we carry it with the letter.</em></strong></figcaption></figure><h3>Infrastructure in Java</h3><p>The cloud target is GKE Autopilot, and the infrastructure is CDK Terrain, which is CDK for Terraform, written in Java so I didn’t have to learn a second language during a Java-learning project. Two stacks, the same split my team uses in other projects:</p><ul><li>common: enabled APIs, the Artifact Registry, the regional Autopilot cluster with Workload Identity, and the identity GitHub Actions will use.</li><li>main: everything on the cluster. Operators through Helm (Strimzi, CloudNativePG, KEDA), the <em>same</em> Kafka and Postgres YAML the kind cluster uses, Secrets from sensitive variables, the three services as typed SpringBootService constructs with probes and limits baked in, a CPU autoscaler for the two request-driven services, and a KEDA scaler on consumer lag for the worker, because an LLM call is I/O-bound and CPU tells you nothing about it.</li></ul><p>cdktn synth turns all of that into plain Terraform JSON, and nothing is hidden. The traps were the kind you only meet by doing: the config file must still be named cdktf.json even though the tool is CDKTN, and the Java-to-Terraform bridge refuses a method called metadata() on a construct because a property with that name already exists.</p><h3>No keys anywhere</h3><p>The identity part is the one I care about most. No service-account keys. GitHub’s OIDC token gets exchanged for a short-lived Google credential through Workload Identity Federation, and the provider only trusts tokens whose repository claim equals this one repository. The deployer account holds two roles, one for the cluster and one for the registry. Nothing static to leak, nothing to rotate, nothing to paste into a secret at midnight. Prefer identities that are asserted over secrets that are stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVuQdqrp6zbRHtC58wvOYQ.png" /><figcaption><strong><em>A signed statement of where you run, instead of a secret that proves who you are.</em></strong></figcaption></figure><h3>CI that builds only what changed</h3><p>CI went through two designs. The first had four workflows with hand-written paths: filters, and it couldn&#39;t say &quot;the contracts module changed, so every service must be rebuilt&quot; without copying the dependency graph into YAML.</p><p>The second uses Buck2 as a thin task runner. BUCK files declare what each step reads and writes: the root pom, the contracts jar, each service&#39;s verify and image targets, the infra synth, plan and apply targets. Maven still does the real work inside a sandbox copy of the declared sources. One query answers &quot;what does this diff affect?&quot;:</p><pre>buck2 uquery &quot;rdeps(//..., owner(&#39;contracts/src/main/java/.../EventEnvelope.java&#39;))&quot;</pre><p>A contracts change rebuilds everything, a README change builds nothing, a change to a single service builds that service. A service’s docker target is its tests followed by an image push under the branch tag, and the main stack resolves that tag to a digest at apply time, so deployments are pinned to a digest even though the tag moves. The push pipeline is three commands: build what changed, apply the stacks behind an approval gate, run the e2e suite against the rolled-out cluster. The PR pipeline builds and pushes under the PR&#39;s branch tag and comments the Terraform plan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYtE0R4ezNbUYxaAfDodHA.png" /><figcaption><strong><em>The push pipeline. Buck2 decides what to build; a human decides whether to deploy.</em></strong></figcaption></figure><p>A small confession: I wanted to put the Buck2 rules in a directory called buck/, and macOS refused, because its file system is case-insensitive and there was already a file called BUCK next to it. The rules live in tools/buck2/ now. Not every architecture decision is deep. Some are just your operating system being picky.</p><p>The e2e job needed one more trick. Kafka clients don’t stay on the bootstrap address; they reconnect to the broker’s <em>advertised</em> hostname, which on Kubernetes is an internal DNS name. A port-forward to the bootstrap service alone isn’t enough. On the CI runner, that hostname is mapped to 127.0.0.1 in /etc/hosts, and with a single broker on port 9092 one forward covers both. It works, it&#39;s documented, and it stops working the day there&#39;s a second broker, which is also documented.</p><h3>What I did not do</h3><p>Here’s the honest part. <strong>I never deployed to GKE.</strong> The stacks synthesize, the workflows are written and reviewed, the e2e job is wired, and the triggers are switched off: both workflows run only by hand. The cloud path costs actual money, and two weeks were two weeks. Everything a stranger needs to go live is in the runbook and in an ADR that lists every deliberate cut: real provider runs (verified only against WireMock), the GKE deployment, an MCP client, KEDA on the local cluster, Kafka TLS, per-partition outbox pollers, and a few more. Each with the reason and the way back in.</p><p>I’d rather you read that paragraph here than discover it in the repo. A project that’s honest about its own edges is more useful than one that claims a cloud it never touched.</p><h3>What I’d change with more time</h3><ul><li><strong>Schema Registry and Avro</strong> instead of JSON Schema and fixture tests, the day more than one team touches the contracts.</li><li><strong>Per-partition outbox pollers.</strong> With several poller replicas, SKIP LOCKED lets a newer row overtake an older one. The saga guards absorb it, but strict ordering only holds with a single poller.</li><li><strong>An orchestrator</strong>, the day the saga passes five steps or gains a human approval step.</li><li><strong>ArgoCD</strong> instead of push deploys, the day a second cluster appears.</li><li><strong>A key-to-user mapping</strong>, so the user id isn’t a header you have to take on faith.</li></ul><h3>So, what is this thing called a saga?</h3><p>It’s what you get when you take “no shared database, no shared code, only events” seriously and then ask what happens to the money when something dies in the middle. The answer turned out to be three patterns holding hands: an outbox so events are never lost, an inbox so duplicates are never harmful, and a transition table so out-of-order events can’t corrupt the state. Add a watchdog for time and compensation for failure, and you get a system that ends every job with exactly one outcome, even when I kill it on purpose, which I did, a lot.</p><p>I started this to turn intermediate Java into working Spring, Kafka and Kubernetes, as a Node.js developer. I finished with something more useful than a list of technologies: a pile of stories about things that broke and why, each one with a test that proves the fix. If you’re on the same road, my one piece of advice is to build the dual-write bug on purpose first. You’ll never forget it, and it makes a great interview answer.</p><p>The repository is <a href="https://github.com/remidosol/llm-mcp">llm-mcp</a> on my GitHub. Clone it, run the smoke test, send a [SLOW] prompt, and kill the worker. Then tell me what you saw.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83d99353424a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #6: Kubernetes on my laptop]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-6-kubernetes-on-my-laptop-b3dc8f9fe2d3?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3dc8f9fe2d3</guid>
            <category><![CDATA[strimzi]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[kraft]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Fri, 18 Sep 2026 19:17:09 GMT</pubDate>
            <atom:updated>2026-09-18T19:17:09.924Z</atom:updated>
            <content:encoded><![CDATA[<p>Docker Desktop asked for 8 GB of memory. I said yes. This is the story of Phase 6: three services, Kafka, Postgres and Redis on a local Kubernetes cluster, run by operators instead of by me, plus one probe I broke on purpose and one bug that looked perfectly healthy.</p><h3>Images without a Dockerfile</h3><p>The services are built into images by Jib, straight from Maven. No Dockerfile, no Docker daemon needed to push. Jib computes layers from the Maven model: dependencies, snapshot dependencies, resources, classes. Change one line of code and only the last, tiny layer is rebuilt and reloaded, which matters when you’re rebuilding twenty times an afternoon. jib:dockerBuild feeds the local daemon for kind, jib:build pushes straight to a registry in CI.</p><p>Apple Silicon trap: Jib’s default platform is amd64. On an arm64 laptop that produces images that run under emulation and quietly eat your CPU. One property, -Dcontainer.arch, defaults to arm64 locally and flips to amd64 for the cloud.</p><h3>The cluster, and who runs what</h3><p><strong>kind</strong> creates the cluster: one control plane, one worker, and a port mapping so job-service is reachable on localhost:30080. Four namespaces, one per concern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kRPf9hIyWqCjr5In-7C8sA.png" /><figcaption><strong><em>What runs where on kind. Each box group is a namespace.</em></strong></figcaption></figure><p>Kafka runs under the <strong>Strimzi</strong> operator as custom resources: a KafkaNodePool, a Kafka resource in <strong>KRaft</strong> mode, and six KafkaTopic resources, which is the declarative version of the init script Docker Compose used. Postgres runs under CloudNativePG: one Cluster, three managed roles, three Database resources. The operators know the annoying parts of stateful workloads (identity, disks, ordered restarts, rebalancing). I write a resource, the operator reconciles reality toward it. That&#39;s the whole point of a CRD: you teach the API server a new noun, and a controller makes the world match.</p><p>Yes, one Postgres cluster. Database-per-service is about coupling and ownership, not about the number of processes. Each service connects with its own role and can’t see the others’ tables, which is the guarantee I actually need. Three Postgres clusters on an eight-gigabyte laptop is a capacity decision, and my laptop’s fan voted no. Splitting later is a manifest change, not a code change.</p><p>The app tier itself is plain Kustomize: a base with Deployments, Services and ConfigMaps, and a local overlay that patches images, the NodePort and the demo knobs. Secrets are generated from .env by a script and exist only inside the cluster. Helm is used for exactly one thing, installing Strimzi, because writing a Helm chart for three services that look identical would&#39;ve been templating for values I never vary.</p><h3>The JVM inside a box</h3><p>Every service pod requests 500 millicores and 768 MiB, with a limit of 1 CPU and 1 GiB. The JVM sees the cgroup and takes 75 percent of the limit as heap, through JAVA_TOOL_OPTIONS=-XX:MaxRAMPercentage=75. Hard-coding -Xmx would start lying the day someone changes the limit. Exit code 137 means the <em>whole</em> container went over the limit, not just the heap, which is a distinction that saves you an hour of staring at GC logs.</p><p>Total memory for the full stack on my machine: about 4.9 GiB across the two kind nodes. Under budget, and I was a little proud.</p><h3>Three probes, three questions</h3><p>Every service pod got three probes, and this is where I learned they answer three different questions.</p><ul><li>The <strong>startup probe</strong> gives the JVM time to wake up and find its glasses: 30 attempts, 2 seconds apart, before liveness is allowed to judge. The services actually start in about 9 seconds, so the budget is generous on purpose.</li><li>The <strong>liveness probe</strong> asks “is the process alive” and deliberately checks <strong>no</strong> dependencies. If Kafka is down for a minute you really don’t want Kubernetes restarting every pod in a loop and turning a small outage into a cascade.</li><li>The <strong>readiness probe</strong> checks the database, Redis and Kafka, and only decides whether the pod is in the Service’s endpoint list and receives traffic.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzop2zRdb87NHDcXuyDfDw.png" /><figcaption><strong>The </strong><strong>/nope experiment. The new pod never becomes ready, the old pod keeps serving, nobody gets a 500.</strong></figcaption></figure><p>To prove it, I patched the readiness path of job-service to /nope on purpose and watched the rollout. The new pod passed its startup probe, failed readiness with 404 after 404, and never joined the Service. The rollout stalled. The <em>old</em> pod kept serving every single request on the NodePort like nothing happened. kubectl rollout undo fixed it with zero failed calls. Readiness gates traffic, not the old pod. Three probes, three questions.</p><h3>The first deploy crashed, and that was fine</h3><p>The very first make deploy-local produced three pods in CrashLoopBackOff, twice each, with FATAL: database &quot;job_db&quot; does not exist. The Postgres Cluster was ready, but the Database resources hadn&#39;t been reconciled yet, so Flyway had nowhere to run. Kubernetes healed it by itself: the pods restarted, the databases appeared, Flyway ran, everything went green. I still added a kubectl wait on the Database status to the deploy script, because &quot;it crashes twice and then works&quot; is not a sentence you want in a demo. Kubernetes gives you no ordering between resources. Either you wait, or the application retries. I did both.</p><p>Smoke on the cluster: happy job COMPLETED, [FAIL] job FAILED, user u1 went from 1000 to 997 credits, twelve events in the trail. Timings on the laptop: kind-up about a minute, the first kind-load about three (the three service images are 700 to 875 MB each, the Connect image 1.2 GB), deploy-local about four.</p><h3>RUNNING is not flowing</h3><p>The bug of the phase taught me to distrust green status fields. I moved Debezium under Strimzi, as a KafkaConnect with a four-line Dockerfile that adds the Postgres connector plugin, plus three KafkaConnector resources. Every connector and every task reported RUNNING. Three replication slots active. Publication created. And nothing moved. Jobs sat in CREATED.</p><p>The status was telling the truth about the control plane and nothing at all about the data. The Connect producer log finally admitted UNKNOWN_TOPIC_OR_PARTITION for a heartbeat topic that didn&#39;t exist, because I had switched off topic auto-creation on purpose back in <a href="https://medium.com/p/a34dcd79d658">Part 2</a>. Debezium wants a heartbeat topic per connector, the producer was stuck waiting for metadata, and the task looked perfectly healthy while doing so. Three more KafkaTopic resources later, the backlog of four jobs drained by itself.</p><p>Bonus lesson from the same run: the one outbox row written <em>before</em> the replication slot existed was never published, exactly as snapshot.mode=no_data promises. The <a href="https://medium.com/p/0c26c9d539a7">Part 3</a> rule, &quot;cut over to CDC with an empty outbox&quot;, held on Kubernetes too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jiNCTN110FoHUFIW2bCD1g.png" /><figcaption><strong><em>RUNNING is not flowing.</em></strong></figcaption></figure><h3>Chaos, the polite version</h3><p>In <a href="https://medium.com/p/1900a1bb192d">Part 4</a> I killed the worker with kill -9 and watched the inbox roll back and Kafka redeliver. On Kubernetes I deleted the worker pod six seconds into a [SLOW] job, expecting the same show. I got the opposite: one LlmStarted, one LlmSucceeded, one attempt row. Why? kubectl delete pod sends SIGTERM, the grace period is 30 seconds, and Spring&#39;s graceful shutdown let the in-flight listener finish its call, commit, write the outbox row, and <em>then</em> exit. No redelivery needed.</p><p>kill -9 and a pod delete give the same final result through two different mechanisms: one through the inbox and redelivery, one through graceful shutdown. I like knowing both, mostly because interviewers like asking about both.</p><p>Two more small ones: scaling the worker to two replicas split the three partitions as 2 + 1 between the members, visible in the consumer group description; scaling back to one gave all three to the survivor. And the job in the pod-delete experiment still ended TIMED_OUT, because the local timeout is 20 seconds and the fake provider&#39;s slow delay is 30, so its result was stored as late = true. Every piece of <a href="https://medium.com/p/1900a1bb192d">Part 4</a> behaved the same on Kubernetes.</p><h3>What I could explain after Phase 6</h3><ul><li>Whether you can talk to a pod that isn’t ready (yes, with exec; the Service just doesn&#39;t send it traffic).</li><li>With a 1 GiB limit and 75 percent, how big the heap is and where the rest goes.</li><li>Why the Kafka resource has no replicas field (the node pool has).</li><li>The first thing to check when a CloudNativePG Database says applied: false.</li><li>Whether two job-service replicas can process the same JobCreated at once (no: one consumer group, plus the inbox).</li></ul><p>Next time: the cloud path in Java, a CI pipeline that only builds what changed, no keys anywhere, and one trace that survives the outbox. Also the part where I admit what I didn’t deploy.</p><p><a href="https://medium.com/p/83d99353424a"><strong>Part:</strong> 7</a> (Final)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3dc8f9fe2d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #5: An MCP server, a circuit breaker, and an API key]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-5-an-mcp-server-a-circuit-breaker-and-an-api-key-ea2d0b09060a?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea2d0b09060a</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 18:28:48 GMT</pubDate>
            <atom:updated>2026-09-17T18:29:38.966Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/p/1900a1bb192d">Part 4</a> finished the saga. Part 5 makes it usable by something that isn’t curl, makes it survive a provider that answers 429 twenty times in a row, and puts a lock on the door. Three topics, two days, and a fake OpenAI that I abused heavily.</p><h3>MCP: a second door into the same rooms</h3><p>If you haven’t met MCP yet: the Model Context Protocol is how an LLM client like Claude Code talks to tools. A tool has a name, a description and a JSON Schema for its arguments; the client reads the list, decides which tool to call, and gets a text result back. It’s REST for a reader that’s very good at language and very bad at guessing.</p><p>job-service grew a second inbound adapter next to its REST controller: three tools (create_job, get_job, list_jobs), one resource (job://{jobId}/result), one prompt (compare_models, which tells the model how to run the same prompt on two models and compare), and argument completion for model names. In Spring AI these are annotations on plain methods: @McpTool, @McpResource, @McpPrompt, @McpComplete. The method parameters become the input schema, the return value becomes the result text, and exceptions become an isError result that the LLM can read and react to. HTTP still says 200, because from the protocol&#39;s point of view the tool ran; it just ran badly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZlMUWGhpEaQNJIN5Ra_6LA.png" /><figcaption><strong><em>REST and MCP are two adapters around the same use cases. The use cases don’t know which door you came through.</em></strong></figcaption></figure><p>The important part is what did <em>not</em> happen. I didn’t build an “AI gateway” service. The MCP tools call the exact same CreateJobService and JobQueryService as the REST controller, validate the same DTO with the same validator, and map exceptions the same way. This is the day the hexagonal layering from <a href="https://medium.com/p/11b0f1533e73">Part 1</a> pays for itself: when the second adapter shows up, the use cases don&#39;t even look up.</p><p>Transport choice: stateless Streamable HTTP. Every call is one independent JSON-RPC request over POST, no session, no server-sent events. That means two replicas behind a Kubernetes Service work with zero session affinity. What I gave up is server-to-client notifications (progress, sampling), which a pipeline of short tools doesn’t need. One rule-four catch: the endpoint property for the stateless mode is still spring.ai.mcp.server.streamable-http.mcp-endpoint, there is no stateless.* prefix, and I know that because I read the auto-configuration bytecode instead of guessing.</p><p>I checked the whole surface with the MCP Inspector CLI (tools/list, tools/call, resources/read, prompts/get) and then, as a last smoke test, drove the same tools from Claude Code. Watching an LLM client create a job that reserves credits to run a prompt through another LLM is a strange little loop, and I enjoyed it more than I should have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlsyONCRdXJWIVFitA7BGg.png" /><figcaption><strong><em>An LLM ordering an LLM job through a very small window.</em></strong></figcaption></figure><h3>The resilience chain, in the right order</h3><p>On the worker side, every provider call now passes through a chain: a Redis token bucket, then a retry, then a circuit breaker, then the provider. The order <em>*is*</em> the design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JH3_r62OnIKrr84emLflnw.png" /><figcaption><strong><em>Outermost first. The bucket guards the quota, the retry only touches errors that can heal, the breaker stops the storm.</em></strong></figcaption></figure><ul><li>The <strong>bucket</strong> sits outside so retries never spend extra quota: one token per delivery, no matter how many tries happen inside.</li><li>The <strong>retry</strong> sits outside the breaker so every attempt is a breaker sample and obeys its decision. An open breaker ends the retry loop right away, because “call not permitted” isn’t a retryable provider failure. Put the retry inside instead and you get a loop that politely waits three times for a breaker that’s telling you to go away.</li><li>The <strong>breaker</strong> only counts retryable failures. A 400 is the caller’s fault, not the provider’s health.</li><li>The provider SDKs’ own retries are switched off, so this is the only retry layer and every attempt shows up in metrics.</li></ul><p>The token bucket is one Lua script in Redis, because provider quotas are per account, not per pod, and “read the counter, decide, write it back” on Redis is a race the moment you have two workers. A script runs atomically. If no token arrives within five seconds, the call is shed with a retryable failure and a metric called ratelimit.rejected, and the saga compensates as usual. Back-pressure first, load shedding second.</p><h3>The fake OpenAI I abused</h3><p>I tested the OpenAI adapter against WireMock, a fake HTTP upstream you can script. The three scenarios that mattered:</p><ul><li>429, 429, 200: the retry works, three tries, one LlmSucceeded, tries=3 in the log.</li><li>Ten 500s in a row: the breaker opens, and the eleventh call never leaves the process. WireMock can prove that by counting requests.</li><li>A normal 200 with token usage: the actual cost is computed from prompt and completion tokens, and it’s always less than or equal to the estimate.</li></ul><p>The before-and-after that I like telling: before this phase, a [FLAKY] prompt needed a Kafka redelivery to heal, which also meant a second LlmStarted and a guard rejection over in job-service. After it: one delivery, one attempt row, one LlmSucceeded. Same input, one fewer moving part.</p><h3>A lock on the door</h3><p>Security got the minimum that isn’t embarrassing. A OncePerRequestFilter reads the X-API-Key header, maps it to a user role or an admin role, and Spring Security&#39;s filter chain decides who may do what: every /api call needs a key, the top-up endpoint needs an admin key, health and metrics endpoints stay open for the cluster. Stateless, no CSRF (there&#39;s no browser session), and the 401 and 403 bodies are RFC 9457 problem details like every other error in the project.</p><p>If you come from Express: the security filter chain is your middleware stack, but in two layers. The filter only establishes <em>who</em> you are. The authorization rules decide <em>what</em> you may do. Two concerns, two classes, and a much easier conversation when someone asks where the line is.</p><p>A trap worth sharing: the filter is deliberately <em>not</em> a @Component. Spring Boot registers every Filter bean with the servlet container as well, so a filter that&#39;s both a bean and part of the security chain runs twice. The kind of bug that only shows up as &quot;why is this log line duplicated&quot;.</p><p>The X-User-Id header is still trusted, and the ADR says so out loud. A key-to-user mapping sits on the &quot;not done&quot; list. I&#39;d rather have an honest list than a fake login page.</p><h3>Small things that made the phase feel finished</h3><ul><li>Readiness now checks the database, Redis <em>and</em> Kafka, with a custom Kafka health indicator (Boot 4 doesn’t ship one). Liveness checks none of them, for reasons <a href="https://medium.com/p/b3dc8f9fe2d3">Part 6</a> will make painfully clear.</li><li>Every log line carries the job id through the MDC, set once in the inbox handler, because every event’s correlation id is the job id. In the cloud profile logs are JSON, so the job id becomes a field you can filter on.</li><li>The breaker’s health component turned out to be opt-in through a second property, management.health.circuitbreakers.enabled=true, which I found by reading the auto-configuration&#39;s conditions. Rule four, again.</li><li>Test counts at the end of the phase: contracts 28, job-service 103, credit-service 28, llm-worker 21, plus four e2e scenarios.</li></ul><h3>What I could explain after Phase 5</h3><ul><li>Why the rate limiter is the outermost layer, and why the retry is outside the breaker.</li><li>What happens with a count-based breaker window of 10 after four failures in a row (nothing: the minimum number of calls isn’t reached yet).</li><li>Why the bucket is a Lua script and not INCR plus EXPIRE.</li><li>Why you can’t accept a session object in a stateless MCP tool.</li><li>Which component produces the 401 and which one the 403.</li></ul><p>Next time: the whole thing moves onto a Kubernetes cluster on my laptop, and I learn that three probes are three different questions.</p><p><a href="https://medium.com/p/b3dc8f9fe2d3"><strong>Part:</strong> 6</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea2d0b09060a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #2: Kafka fundamentals, and a bug I wrote on purpose]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-2-kafka-fundamentals-and-a-bug-i-wrote-on-purpose-a34dcd79d658?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a34dcd79d658</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 18:28:18 GMT</pubDate>
            <atom:updated>2026-09-17T18:28:18.174Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/p/11b0f1533e73">Part 1</a>, one service learned to behave. In Part 2 it gets a neighbor, and they start talking through Kafka. This is also the phase where I wrote a data-loss bug on purpose, with a log line that says DUAL-WRITE LOSS, and left it in the code for two days. I&#39;ll explain.</p><h3>The contract comes first</h3><p>Before credit-service existed, the contracts module did. It&#39;s the only code shared between services, so it deserves to be boring and strict. Every Kafka record carries the same envelope:</p><pre>{<br>  &quot;eventId&quot;: &quot;0192e6a3-…&quot;,          // UUIDv7: time-ordered<br>  &quot;eventType&quot;: &quot;JobCreated&quot;,<br>  &quot;eventVersion&quot;: 1,<br>  &quot;occurredAt&quot;: &quot;2026-09-13T10:15:00Z&quot;,<br>  &quot;aggregateType&quot;: &quot;job&quot;,<br>  &quot;aggregateId&quot;: &quot;…jobId…&quot;,<br>  &quot;correlationId&quot;: &quot;…jobId…&quot;,       // the whole saga shares it<br>  &quot;causationId&quot;: &quot;…eventId…&quot;,       // the event that caused this one<br>  &quot;producer&quot;: &quot;job-service&quot;,<br>  &quot;payload&quot;: { &quot;userId&quot;: &quot;u1&quot;, &quot;prompt&quot;: &quot;…&quot;, &quot;model&quot;: &quot;fake:demo&quot;, &quot;estimatedCredits&quot;: 12 }<br>}</pre><p>Twelve event types, a JSON Schema for each plus one for the envelope, a fixture file per event, and a test that fails when someone changes a contract by accident. Someone was usually me. Consumers dispatch on the eventType string, not on a Java class name, so a producer can refactor its classes without breaking anyone. Unknown fields are ignored (the tolerant reader), and anything that isn&#39;t additive goes on a new topic version. About 450 bytes per event. Kafka doesn&#39;t even notice.</p><p>Why JSON and not Avro with a Schema Registry? Because I’m one team, and a schema that’s a build-time test is the right size for one team. The registry is the upgrade path, and I can say exactly what would trigger it: a second team or a non-JVM consumer.</p><h3>Keys, partitions, and ordered gossip</h3><p>The Kafka key is the job id. That one decision buys you ordering: every event of a job lands on the same partition, in order. With a random key, LlmSucceeded could overtake LlmStarted and you&#39;d never sleep again. Kafka is gossip, but ordered gossip, if you pick your keys well.</p><p>One topic per producing service, three partitions each, versioned in the name: job.events.v1, credit.events.v1, llm.events.v1. Three partitions means at most three active consumers per group, which is plenty for a laptop, and a .v2 topic is the migration path if that ever changes. Each service is one consumer group, so credit.events.v1 can be read independently by job-service and by llm-worker, each with its own offsets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaBe_IEp4Gv_sZn1Cw_0Ag.png" /><figcaption><strong><em>Key = job id. Everything about one job stays on one partition, in order.</em></strong></figcaption></figure><p>The thing I wrote in bold in my notes: ordering is guaranteed only <em>inside</em> a partition. Between two topics there’s no ordering at all. job-service will listen to two topics in <a href="https://medium.com/p/1900a1bb192d">Part 4</a>, and yes, that comes back.</p><h3>Coming from Pub/Sub</h3><p>Some context: for more than a year my day job has been Google Cloud Pub/Sub with push subscriptions. Pub/Sub POSTs each message to an HTTP endpoint, the endpoint answers 2xx, and that’s the ack. It’s a very comfortable model, and it made Kafka feel strange for about two days. The differences that actually changed how I wrote code:</p><ul><li><strong>Who calls whom.</strong> In Pub/Sub, the broker calls me: a push subscription hits my endpoint and I never think about polling. In Kafka, I call the broker: the consumer pulls a batch, processes it, and commits an offset. That one inversion gives Kafka natural backpressure. A slow consumer simply pulls less. With push, my only backpressure was “answer with a non-2xx and hope the retry backoff is polite”, and on Cloud Run a burst of messages turned into a burst of instances before I could say “max instances”.</li><li><strong>What “topic” means.</strong> Pub/Sub has no partitions to think about; it just scales. A topic in Kafka is three partitions I chose myself, and that number is a cap: at most three consumers in a group do useful work. Nothing in Pub/Sub ever made me choose a number like that.</li><li><strong>Subscription versus consumer group.</strong> The closest match: a Pub/Sub subscription is a Kafka consumer group. Every subscription gets every message, and subscribers sharing one subscription share the messages. That’s how job-service and llm-worker both read credit.events.v1 here: two groups, two independent offsets, same records. The mental model transfers well, the vocabulary doesn&#39;t.</li><li><strong>Ordering.</strong> In Pub/Sub, ordering is off by default and you opt in with an ordering key. With push, messages with the same key are delivered one at a time, in order, and a failing message holds the others behind it. In Kafka, ordering per key is not a feature you switch on, it’s how partitions work, and a poison record blocks its whole partition until the error handler deals with it. Same shape of problem, different default.</li><li><strong>Replay.</strong> In Pub/Sub, replaying means seeking a subscription to a timestamp or a snapshot, and only if you turned on retention of acked messages. In Kafka the log is just there: start a new consumer group at the beginning and everything comes back. That’s the replay experiment in <a href="https://medium.com/p/1900a1bb192d">Part 4</a>, and it’s the reason the inbox key had to be the <em>logical</em> consumer name and not the group id.</li><li><strong>Dead letters.</strong> Pub/Sub gives you a dead-letter topic with a “max delivery attempts” number and that’s it. In Kafka you build the policy yourself, with the error handler a few paragraphs down: which errors retry, how long, and what goes to &lt;topic&gt;.DLT. More typing, but I can explain every line of it.</li><li><strong>Exactly-once.</strong> Pub/Sub offers exactly-once delivery, but only for pull subscriptions, so with push I never had it anyway. Kafka’s version covers Kafka-to-Kafka flows only. Neither one covers “and then write to my database”. The inbox below is the answer in both worlds, and I wish I had written it a year earlier.</li><li><strong>Small stuff.</strong> Pub/Sub attributes are Kafka headers (I use eventType and eventId the same way I used attributes for filtering). A Pub/Sub message can be 10 MB, Kafka&#39;s default limit is 1 MB, which is one more reason the prompt travels in the event and a 100 KB prompt would travel as a reference instead.</li></ul><p>If I had to summarize it in one line: Pub/Sub sold me convenience and hid the queue, Kafka sold me a log and made me look at it. For a learning project, looking at it was the point.</p><h3>Credits, a semantic lock, and six angry threads</h3><p>credit-service does one job on JobCreated: reserve the estimated credits, or reject. Credits aren&#39;t decremented when reserved. balance stays where it is, reserved grows, and available = balance − reserved. That reserved column is the &quot;semantic lock&quot; from the saga literature: the money isn&#39;t spent, but it can&#39;t be spent by anyone else either.</p><p>The reservation runs under SELECT … FOR UPDATE, which in Spring Data is @Lock(PESSIMISTIC_WRITE) on the repository method. My test fires six threads that all try to reserve 60 out of 100 credits at the same time, and exactly one of them wins. Without the lock all six read 100, all six write, and congratulations, you&#39;ve reserved 360 credits from an account that has 100. That&#39;s the lost-update anomaly from the saga books, reproduced on my laptop in a forty-line test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d0JFXnDN1GdtkgqQcymO_w.png" /><figcaption><strong><em>Six threads, one account, one winner.</em></strong></figcaption></figure><h3>The inbox in five lines</h3><p>Kafka delivers at-least-once. A consumer that crashes after the handler but before the offset commit gets the record again. Reserving credits twice for one job is a real money bug, the kind people write angry emails about. Kafka’s “exactly-once” doesn’t help here: it covers Kafka-to-Kafka flows, not a database write. So every consumer does this inside its own transaction:</p><pre>INSERT INTO processed_event (event_id, consumer_group)<br>VALUES (:eventId, :group)<br>ON CONFLICT DO NOTHING</pre><p>Zero rows affected means “seen it, thanks”, and the handler is skipped and a metric ticks. A crash before commit rolls the claim back, so the redelivery processes the event cleanly. At-least-once on the wire, effectively once in the database.</p><p>Why ON CONFLICT DO NOTHING and not catching the unique-violation exception? Because Hibernate marks the session for rollback on a constraint error, and then your handler is dead anyway. Counting rows is quieter.</p><p>Two subtle choices I’d defend in an interview: the claim is in the <em>same</em> transaction as the side effect (a separate transaction could claim the event and then crash before doing the work), and the key is the <em>logical</em> consumer name, not the Kafka group id. That second one gets its own story in <a href="https://medium.com/p/1900a1bb192d">Part 4</a>.</p><h3>Retry what can heal, quarantine what can’t</h3><p>Not every failure is the same. A database timeout heals by itself. A record that says this is not json never will, and one poison record can block a partition forever. The error handler in each service does five attempts with exponential backoff, one second doubling up to ten, and then publishes the record to &lt;topic&gt;.DLT, the dead-letter topic, with headers that say what went wrong. Unparseable envelopes skip the retries and go straight there. The DLT has a single partition, which needed a custom destination resolver, because the default tries to reuse the source partition number and a one-partition topic doesn&#39;t have a partition 2.</p><p>Three failure classes, three reactions: retry what can heal, quarantine what can’t, and (from <a href="https://medium.com/p/1900a1bb192d">Part 4</a>) ignore what’s merely out of order.</p><h3>The bug I wrote on purpose</h3><p>Now the part I promised. job-service publishes JobCreated to Kafka <strong>right after the database commit</strong>, from an @TransactionalEventListener(AFTER_COMMIT) hook. That&#39;s the classic dual-write bug: two systems, two writes, and a crash between them loses the event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfRkiVulDI5LsBeFFANLiA.png" /><figcaption><strong><em>The dual-write window. Between the commit and the send, the job exists and the event doesn’t.</em></strong></figcaption></figure><p>I wrote it that way deliberately. I even made it log DUAL-WRITE LOSS whenever Kafka was unreachable, then sat there watching a job row stuck in CREATED with no event anywhere. I wanted to <em>see</em> the hole before closing it in <a href="https://medium.com/p/0c26c9d539a7">Part 3</a>. You remember a bug much better when you&#39;re the one who built it, and the before-and-after makes a much better story than &quot;I used the outbox pattern because the book said so&quot;.</p><h3>What the smoke test showed</h3><p>At the end of the phase: a POST for user u1 with a 52-character prompt on an openai model reserved 39 credits (the estimate is ceil(52 / 4) × 3), credit.events.v1 had a CreditReserved with the job id as key and the JobCreated event id as causationId, all within the first second. User u2, who had 5 credits, got a CreditRejected(available=5, requested=17). Consumer lag: zero on every partition. And in kafka-ui I could click on a message and read the whole envelope, which is exactly why I chose JSON.</p><h3>What I could explain after Phase 2</h3><ul><li>Where Kafka guarantees ordering and where it doesn’t.</li><li>What happens, step by step, when a listener throws.</li><li>Why the inbox insert is in the handler’s transaction and not after it.</li><li>The difference between acks=all and enable.idempotence=true (one is about not losing on failover, the other about the producer&#39;s own retries).</li><li>The two exact points in the dual-write timeline where a crash loses data.</li><li>What a Pub/Sub subscription maps to in Kafka (a consumer group), and what has no equivalent at all (choosing a partition count).</li></ul><p>Next time: the transactional outbox, built twice, and the test where I pause Kafka and nothing bad happens.</p><p><a href="https://medium.com/p/0c26c9d539a7"><strong>Part:</strong> 3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a34dcd79d658" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #4: The saga, and why choreography]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-4-the-saga-and-why-choreography-1900a1bb192d?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1900a1bb192d</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 04:50:54 GMT</pubDate>
            <atom:updated>2026-09-16T19:31:55.065Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the post the series is named after. Three services finally dance together, a watchdog gets a stopwatch, a result arrives too late, and I kill a process in the middle of a call to see who cleans up. Spoiler: the database does.</p><h3>The third service and its chaos hooks</h3><p>llm-worker consumes CreditReserved, picks a provider from the model prefix (openai:, gemini:, fake:), records an attempt row, calls the provider, and emits LlmStarted, then LlmSucceeded or LlmFailed, all through the outbox from <a href="https://medium.com/p/0c26c9d539a7">Part 3</a>. The provider choice is a Strategy: one LlmProvider port, three implementations, Spring injects them as a list and the worker picks by prefix.</p><p>The fake provider is the default everywhere, and it has chaos hooks: a prompt starting with [FAIL] fails, [FLAKY] fails twice and then succeeds, [SLOW] sleeps long enough to trigger a timeout. Real providers only wake up when an API key is present, and even then max_tokens is capped at 512, because a learning project shouldn&#39;t teach me about invoices.</p><p>Event-carried state: CreditReserved carries the prompt and the model, copied from JobCreated. The worker never calls job-service to ask &quot;what was the prompt again?&quot;. It costs some duplication on the wire. It buys autonomy: the worker runs with job-service completely down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BEi7b0K20At4JlF0hlFHw.png" /><figcaption><strong><em>Three services, three topics, one direction each. Commands enter only through job-service; after that it’s all events.</em></strong></figcaption></figure><h3>Choreography or orchestration?</h3><p>With orchestration, one service sends commands (“reserve credits”, “run the LLM”) and waits for replies. With choreography, each service reacts to an event, updates its own tables, and emits the next event. There’s no central brain telling everyone what to do.</p><p>I picked choreography, and the ADR explains it in one sentence: with three steps choreography wins on autonomy, past five steps an orchestrator wins on readability. I know exactly what the orchestrator version would look like, command topics, reply correlation, a state machine in job-service, and I just didn&#39;t need it yet. Knowing the version you didn&#39;t build is, I think, the difference between a decision and a habit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z31KmWiUE0UgATepYLdMvw.png" /><figcaption><strong><em>Above: three services that react. I built the right one, and I can draw the left one. Below: a brain that gives orders.</em></strong></figcaption></figure><p>So where does the saga state live? Only in job-service, in the status column of the job row, guarded by the transition table from <a href="https://medium.com/p/11b0f1533e73">Part 1</a>. credit-service and llm-worker keep only their own local state and emit facts, never commands.</p><p>The three steps also have names in the saga literature, and knowing them helps: reserving credits is <em>compensatable</em> (release undoes it), the LLM call is a <em>pivot</em> (once it happened you can’t un-happen it, you can only pay for it), and capturing the cost is <em>retriable</em> (idempotent, it must eventually succeed). The design of every compensation path follows from those three labels.</p><h3>Out of order, and the path an event implies</h3><p>Then reality knocked, exactly where <a href="https://medium.com/p/a34dcd79d658">Part 2</a> said it would. Events of one job travel across three topics, and ordering is only guaranteed <em>within</em> a partition. So LlmSucceeded can arrive at job-service before LlmStarted, or even before CreditReserved. Rejecting a perfectly good result because its predecessor is late would be silly.</p><p>Instead, an event implies its predecessors. A small class called SagaPath knows that LlmSucceeded while the job is still CREATED means the path CREDIT_RESERVED → PROCESSING → COMPLETED, and walks it. Only truly backwards or terminal moves (a LlmStarted arriving after COMPLETED, say) get rejected, counted in a metric called saga.guard_rejected, and ignored. Not retried, not dead-lettered. Ignored. Out-of-order delivery is normal life, and the dead-letter topic is for abnormal records.</p><p>My end-to-end test injects an early LlmSucceeded straight onto the topic by hand, then lets the real worker&#39;s events arrive later. One completion, one capture, and two guard rejections in the metrics, exactly as planned.</p><h3>The watchdog and the late result</h3><p>The other half of a saga is time. There’s no orchestrator watching a clock, so a watchdog in job-service runs every 30 seconds, locks jobs that have been sitting in CREDIT_RESERVED or PROCESSING for longer than the timeout (120 seconds in production, 20 locally for demos) with FOR UPDATE SKIP LOCKED, moves them to TIMED_OUT, and emits JobTimedOut. credit-service releases the reservation. Two watchdog replicas can never double-time-out a job, because of the same SKIP LOCKED trick as the poller.</p><p>It measures from updated_at, not created_at. If credit-service is down for ten minutes, a job waits in CREATED for ten minutes and that&#39;s fine. The timeout is about the <em>current</em> step being stuck, not about the job&#39;s age.</p><p>And when the slow provider finally answers? The result is stored with late = true, a metric ticks, and the job <em>stays</em> TIMED_OUT. I refuse to reopen the money question after the user was already told the job failed. The answer is kept as data, the past is not rewritten. That trade-off has its own ADR, because someone will definitely ask &quot;but the answer was right there&quot;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nWsRnRsutQ1ZFz2hV1Fyg.png" /><figcaption><strong><em>The watchdog. It doesn’t cancel anything. It just decides when waiting is over.</em></strong></figcaption></figure><h3>The bug that hid for 60 seconds</h3><p>Remember the cache-aside window from <a href="https://medium.com/p/11b0f1533e73">Part 1</a>? Here it is in practice. My e2e test for [FAIL] polled GET /api/jobs/{id} every 100 ms. The database said FAILED within a second. The API said CREDIT_RESERVED for a full minute.</p><p>The sequence: a GET read the old row just before the saga handler&#39;s commit, the handler evicted the cache entry <em>inside</em> its transaction, then the GET wrote the old value back into the cache, and the 60-second TTL kept it there. Evicting before the commit doesn&#39;t just fail to help, it <em>guarantees</em> a stale read under load.</p><p>The fix was one call on the Redis cache manager, transactionAware(), which delays evictions until after the transaction commits. The remaining window is the few milliseconds between &quot;read from the database&quot; and &quot;write to the cache&quot;, which the TTL bounds. To close it completely you&#39;d need versioned puts or a cache that only stores terminal states. I have a good interview sentence about this now, and I paid for it with an afternoon.</p><p>Side finding of the same afternoon: Spring Boot DevTools’ restart classloader made cached JobView objects fail with JobView cannot be cast to JobView, which is the kind of error message that makes you question your life choices. DevTools left the project that day.</p><h3>Chaos, round one: `kill -9`</h3><p>I sent a [SLOW] job and ran kill -9 on llm-worker in the middle of the call. Here&#39;s what the tables and topics showed afterwards:</p><ul><li>The attempt row stayed half-finished: STARTED, no outcome.</li><li>The inbox claim rolled back, because the claim and the outcome live in the same transaction. No row in processed_event.</li><li>The worker came back, Kafka redelivered CreditReserved, attempt number two ran and succeeded.</li><li>On the topic: two LlmStarted, one LlmSucceeded. The second LlmStarted hit the PROCESSING → PROCESSING guard in job-service, got counted, got ignored.</li></ul><p>One job, one outcome, and I got to feel like a villain for a minute.</p><h3>Chaos, round two: the replay</h3><p>I pointed a brand-new consumer group at credit.events.v1. Kafka delivered all 21 CreditReserved events again from the beginning. The number of LLM attempts went from 20 to… 20. The inbox duplicate counter went to 21. This works because the inbox key is the <em>logical</em> consumer name, not the Kafka group id, so a replay into a new group is still checked against the real processing history. If I had used the group id as the key, a replay would have run twenty LLM calls and reserved nothing new, which is the worst of both worlds.</p><h3>Numbers from the phase</h3><ul><li>Happy path end to end with the fake provider: about 2 to 3 seconds (three poller ticks and two inbox hops).</li><li>e2e suite: four scenarios, 92 seconds, most of it the [SLOW] timeout.</li><li>One worker with the fake provider at 200 ms: about 5 jobs per second. With a real LLM at 2 to 10 seconds: 0.1 to 0.5 jobs per second, which is the whole argument for scaling the worker on consumer lag instead of CPU. That argument comes back in <a href="https://medium.com/p/83d99353424a">Part 7</a>.</li></ul><h3><strong>What I could explain after Phase 4</strong></h3><ul><li>Which step is compensatable, which is the pivot, which is retriable, and why that decides the compensation design.</li><li>What job-service does, exactly, when LlmSucceeded arrives before CreditReserved.</li><li>Why the watchdog measures from updated_at.</li><li>Why a late result doesn’t re-capture credits, and what the user is told.</li><li>What the orchestrator version would look like, and what it would cost.</li></ul><p>Next time: an MCP server so an LLM client can drive the pipeline, a circuit breaker for when the LLM provider is having a day, and an API key so strangers can’t spend my credits.</p><p><a href="https://medium.com/p/ea2d0b09060a"><strong>Part:</strong> 5</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1900a1bb192d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #3: The transactional outbox, twice]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-3-the-transactional-outbox-twice-0c26c9d539a7?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c26c9d539a7</guid>
            <category><![CDATA[debezium]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[outbox-pattern]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Wed, 16 Sep 2026 04:49:55 GMT</pubDate>
            <atom:updated>2026-09-16T19:31:09.181Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/p/a34dcd79d658">Part 2</a> ended with a bug I wrote on purpose: publish after commit, lose the event if the process dies in between. This post closes the hole, then closes it a second time in a completely different way, and proves the two ways are the same on the wire.</p><h3>Why not just retry, and why not 2PC</h3><p>Two obvious answers, both wrong.</p><p>“Just retry the send.” Retries can’t cover a crash between the commit and the send, because there’s nobody left to retry. The process is gone and the job row sits there with no event.</p><p>“Use a distributed transaction.” Kafka doesn’t participate in two-phase commit, and even if it did, a 2PC coordinator is a single point of failure that ties the availability of Postgres and Kafka together: if either is slow, both are. The saga books call this out clearly, and I didn’t want to learn it the expensive way.</p><p>The actual answer: write once, to one place, atomically, and publish from there asynchronously with retries.</p><h3>The outbox: same transaction, different table</h3><p>The state change and the event get written in <strong>one database transaction</strong>. The use case publishes an in-process domain event, a synchronous @EventListener appends the full envelope to an outbox table, and the whole thing commits together. If the job insert commits, the outbox row commits. If either fails, neither exists. No more hole.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MBl43xB6ilPTELpri7Z1w.png" /><figcaption><strong><em>One transaction writes two rows. Someone else’s job is to move the second one to Kafka.</em></strong></figcaption></figure><p>The table uses Debezium’s default column names (id, aggregatetype, aggregateid, type, payload) from day one, plus published_at. That was rule four again: I read the Debezium docs before designing the table, so the second publisher later needed almost no configuration.</p><h3>Publisher number one: the poller</h3><p>A scheduled method runs every 500 milliseconds inside a transaction. It claims up to 100 unpublished rows with:</p><pre>SELECT … FROM outbox<br>WHERE published_at IS NULL<br>ORDER BY id<br>LIMIT 100<br>FOR UPDATE SKIP LOCKED</pre><p>then sends each one to Kafka synchronously (send().get() with a ten-second timeout), marks published_at, and commits. If Kafka is down, the send throws, the transaction rolls back, and the rows just wait for the next tick. ORDER BY id works because the ids are UUIDv7, which means time order. SKIP LOCKED means two pollers never fight over the same rows. That&#39;s the whole publisher, about eighty lines, and I own every one of them.</p><p>Small Node-brain moment: @Scheduled and @Transactional on the <em>same</em> method work fine, because the scheduler calls the method through the proxy. It&#39;s the self-invocation rule from <a href="https://medium.com/p/11b0f1533e73">Part 1</a> in reverse: the call comes from outside, so the proxy is in the loop.</p><h3>My favourite test in the whole project</h3><pre>pause the Kafka container<br>create three jobs          → all three get 202, the API doesn&#39;t even notice<br>wait six seconds           → three rows pending, published_at is null<br>unpause Kafka<br>wait                       → all three rows marked, three records on the topic</pre><p>Testcontainers can pause a container with one call, which makes this a normal integration test, not a manual exercise. The write path never touches Kafka. That&#39;s the entire point of the pattern, and you can show it in one test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSBCFculTEOZK4bXuQXnSA.png" /><figcaption><strong><em>Kafka goes away for six seconds. Nobody loses anything.</em></strong></figcaption></figure><h3>Publisher number two: Debezium</h3><p>Then I built the second publisher. Debezium’s Postgres connector reads the write-ahead log (<em>WAL</em>), which is basically the database’s diary, sees the outbox inserts, and its EventRouter transformation publishes the payload column as the record value to &lt;aggregatetype&gt;.events.v1, with the same key and the same headers. Postgres needs wal_level=logical (I had set it in Docker Compose since day one, again thanks to reading ahead), the connector opens a replication slot, and snapshot.mode=no_data makes sure rows written before the slot existed are never re-published.</p><p>One property switches between the two: app.outbox.publisher=polling|cdc. In CDC mode the poller bean simply doesn&#39;t exist, and outbox rows never get a published_at, which is actually a nice proof that Debezium did the publishing and not the poller. The bytes on Kafka are identical, and the same consumer tests prove it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-3b0dIShKthuvEdynlj2g.png" /><figcaption><strong><em>Debezium reads the database’s diary.</em></strong></figcaption></figure><p>Why build both? Because the poller is readable and testable with a paused container, and Debezium is an operator, a replication slot, and a rabbit hole with its own weather. Building the simple version first meant I understood exactly what the fancy version was doing for me. And when Connect is having a bad day, the poller is one property away.</p><p>The numbers on my laptop: poller mode goes from POST to CreditReserved in under a second; CDC mode takes about two to four (Debezium&#39;s own poll interval plus Connect flushing). CDC doesn&#39;t win on latency here. It wins on not querying the database at all and on not caring how many poller replicas exist.</p><h3>What CDC costs</h3><ul><li><strong>Slot bloat.</strong> If the connector is down, Postgres keeps every WAL segment the slot hasn’t consumed. On my laptop the retained WAL sat at 6 to 17 KB. In production it can be gigabytes, and it’s the database’s disk, not Kafka’s.</li><li><strong>Schema changes to the outbox now involve the connector.</strong> In <a href="https://medium.com/p/83d99353424a">Part 7</a> this bites me in a very specific order.</li><li><strong>Another cluster to run.</strong> Kafka Connect is its own thing with its own logs and its own moods.</li></ul><p>There’s also a cute trick I documented but didn’t use: with CDC you can insert the outbox row and delete it in the same transaction. The insert is still in the WAL, Debezium still sees it, and the table never grows. I skipped it because on a laptop I like being able to look at the rows.</p><h3>Still not exactly-once</h3><p>The poller can send successfully and then fail to mark the row, which gives you a duplicate. A paused broker can deliver a record from the producer’s buffer after unpause <strong>and</strong> the poller can send it again. Debezium has its own retries. So outbox-to-Kafka is at-least-once, and that’s exactly why every consumer has the inbox from <a href="https://medium.com/p/a34dcd79d658">Part 2</a>. The two patterns come as a pair, like socks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nzkzAESVDt27bxLjGlDqw.png" /><figcaption><strong><em>The duplicate the outbox can produce, and the inbox that makes it harmless. Send once more, process once.</em></strong></figcaption></figure><p>Read the picture bottom-up and you have the whole reliability story of this project in one screen: the outbox guarantees the event leaves at least once, the inbox guarantees it lands exactly once, and neither of them needs the other to be perfect.</p><h3>What I could explain after Phase 3</h3><ul><li>At what moment the outbox row becomes durable, and what happens to it if the job insert fails.</li><li>What SKIP LOCKED buys you and what ordering risk it creates with two pollers (a newer row can overtake an older one that&#39;s still being sent; the saga guards in <a href="https://medium.com/p/1900a1bb192d">Part 4</a> tolerate it).</li><li>What a three-hour connector outage does to Postgres, and how you’d notice.</li><li>Which fields of the Kafka record the poller and Debezium must produce identically, and why.</li></ul><p>Next time: the third service, the saga itself, and a kill -9 I enjoyed a little too much.</p><p><a href="https://medium.com/p/1900a1bb192d"><strong>Part:</strong> 4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c26c9d539a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #1: Foundation, or Java for a Node person]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-1-foundation-or-java-for-a-node-person-11b0f1533e73?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/11b0f1533e73</guid>
            <category><![CDATA[cdktf]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[mcp-server]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 00:05:07 GMT</pubDate>
            <atom:updated>2026-09-16T19:29:53.548Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/p/d771dd586f84">Part 0</a> explained why I built llm-mcp. This one is about the first week: getting a single service to behave, and meeting Java’s habits with my Node.js habits still in my pockets.</p><p>The goal for the week was small on paper: job-service with a database schema, a Job entity, a state machine, a REST API, a Redis cache, and integration tests against the real thing. The definition of done was one sentence: POST /api/jobs returns 202, GET returns the job, and the second GET is served from Redis, visibly, in the logs. Small goals, big surprises.</p><h3>The layout inside a service</h3><p>Every service in the project has the same four packages, and I kept that shape from day one:</p><pre>api/             inbound adapters: REST controllers, DTOs, error handler<br>application/     use cases, ports, read models<br>domain/          the aggregate, the state machine, domain events<br>infrastructure/  persistence, messaging, cache, security</pre><p>Call it hexagonal-lite. Ports and adapters where the arrows matter, pragmatism where they don’t. The domain package may not import Spring. The API layer may not touch infrastructure. The application layer reaches outward only through its own port interfaces. I didn’t write these rules in a wiki. I wrote them as ArchUnit tests, so the build fails when someone (me, on a Friday) breaks them.</p><p>One conscious shortcut: the JPA entity <em>is</em> the aggregate. A pure domain model with a separate persistence model doubles the class count, and I wanted to learn the JPA lifecycle, not hide it. The price is three rules: no setters, every state change through a domain method, and no Spring in the domain. Lombok is allowed only on entities and only for @Getter and a protected no-args constructor. @Data on an entity is banned, because equals and hashCode over mutable fields make entities disappear from hash sets, and that&#39;s a bug you find at 2 a.m.</p><h3>The state machine as a table</h3><p>A job has seven states and eight legal transitions. The classic State pattern says: one class per state. My states differ only in which transitions they allow, so seven classes plus an interface would’ve been pure ceremony. I wrote a table instead:</p><pre>Map&lt;JobStatus, Set&lt;JobStatus&gt;&gt; ALLOWED = Map.of(<br>    CREATED,         Set.of(CREDIT_RESERVED, REJECTED),<br>    CREDIT_RESERVED, Set.of(PROCESSING, FAILED, TIMED_OUT),<br>    PROCESSING,      Set.of(COMPLETED, FAILED, TIMED_OUT)<br>);</pre><p>If you know XState, it’s the states: { on: { … } } object with less punctuation. Terminal states aren&#39;t in the map at all, which gave me my first Java bug of the project. More on that in a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PpkoJ2wTMKWrvZt4Nx2w_Q.png" /><figcaption><strong><em>Seven states, eight legal moves. Everything else is rejected by one method.</em></strong></figcaption></figure><p>The test for this table is a 7×7 matrix: 49 pairs, 8 true, 41 false, and “an invalid transition never changes the state”. Boring test, but in <a href="https://medium.com/p/1900a1bb192d">Part 4</a> the saga handlers call this exact method with exactly these inputs, and I sleep better knowing it was tested to death.</p><h3>Meeting the Spring proxy</h3><p>This was the day I met the Spring proxy. In Spring, annotations like @Transactional and @Cacheable work through a proxy object wrapped around your bean. Call a method on this from inside the same class and the proxy is skipped, so the annotation quietly does nothing. No error, no warning, nothing in the logs. It&#39;s like that friend who only listens when you call them by their full name.</p><p>For a Node developer it feels like calling a route handler directly instead of going through the router: the middleware never runs. My rule now: a transaction boundary is always a call <em>between</em> beans, never inside one. That’s why the project has separate CreateJobService, JobQueryService and JobTransitionService classes instead of one fat service with private helpers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xg5aeQP9ViqJ3Q4fMVd_4Q.png" /><figcaption><strong><em>The proxy only sees calls that come from outside the bean.</em></strong></figcaption></figure><p>The transaction boundary itself lives in the use case, not in the controller. Putting it on the controller would keep the transaction open for the whole HTTP request. Putting it on the use case keeps it as short as the business operation. In <a href="https://medium.com/p/0c26c9d539a7">Part 3</a> the outbox row will be written inside this exact boundary, so getting it right in day one mattered more than it looked.</p><h3>Virtual threads versus the event loop</h3><p>Spring MVC runs every request on its own thread. With spring.threads.virtual.enabled=true those become cheap virtual threads, so blocking code like JDBC parks the virtual thread instead of blocking a real one. Same scaling goal as the Node event loop, opposite ergonomics: Node pushes you into async APIs, Java lets you keep writing boring blocking code. CPU-bound work is still CPU-bound, sorry. There&#39;s no magic, just a scheduler that&#39;s good at waiting.</p><h3>Real databases in tests, or nothing</h3><p>Every integration test runs against a real Postgres and a real Redis, started by Testcontainers. No H2. H2 happily passes tests that Postgres fails: different dialect, no jsonb, and later in the project no SKIP LOCKED. A green test against a database you never run in production is a lie with a nice color.</p><p>Spring Boot’s @ServiceConnection was a small joy here. You annotate the container bean and Boot wires host, port and credentials into the application by itself. No property files with ${PORT} placeholders. The containers start once per test run, and the whole job-service suite finishes in about a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*As2__giRiuMUm57eAIb9jA.png" /><figcaption><strong><em>H2 in tests, Postgres in production.</em></strong></figcaption></figure><h3>The cache, and the window I didn’t see yet</h3><p>GET /api/jobs/{id} is cache-aside on Redis: a miss reads the database and fills the cache, every state change evicts the entry, and a 60-second TTL sits there as a safety net in case some new write path forgets to evict. The eviction has exactly one door, JobTransitionService, so nobody can change a job without the cache hearing about it.</p><p>I wrote in my notes that week: “a concurrent reader can still re-cache a stale value between the eviction and the commit; the TTL limits the damage to 60 seconds.” I was right, and in <a href="https://medium.com/p/1900a1bb192d">Part 4</a> that sentence came back to bite me in a very concrete way. Keep it in mind.</p><h3>Rule four earns its keep</h3><p>“Verify, don’t recall.” Three examples from the first two days:</p><ul><li>Spring Boot 4.1 has <strong>no</strong> Docker Compose service connection for Kafka anymore. Boot 3 had one, my design assumed one, the docs table said no. So I set spring.kafka.bootstrap-servers by hand instead of spending an afternoon staring at &quot;connection refused&quot;.</li><li>Putting @Validated on a controller class in Spring Framework 7 doesn&#39;t improve parameter validation. It breaks it. Constraint violations came back as HTTP 500 instead of 400 until I deleted the annotation. An annotation that makes things worse by existing was a new experience for me.</li><li>Map.get(key) returns null for a missing key, and Java has no optional chaining. My transition table threw a NullPointerException on terminal states until I switched to getOrDefault(key, Set.of()). Ten years of obj?.[key] muscle memory don&#39;t die in two days.</li></ul><p>And a fourth one that only a code review caught: I assign the job id myself (UUID.randomUUID()) and my @Version field was a primitive long. Spring Data couldn&#39;t tell whether the entity was new, so every save() did a SELECT before the INSERT. One extra round trip on the hottest write path, completely silent. Making the version field a nullable Long fixed it. You only see this kind of thing if you log the SQL and actually read it.</p><h3>What I could explain after Phase 1</h3><ul><li>Why @Transactional on a private or self-invoked method does nothing.</li><li>Where the transaction boundary goes and why not the controller.</li><li>Why Flyway migrations are immutable (the checksum turns schema drift into a build error).</li><li>Why the @Version column exists (two saga handlers racing on one row won&#39;t overwrite each other).</li><li>What virtual threads change and what they don’t.</li><li>Where cache-aside can still serve a stale read. (Spoiler: I knew the theory. The practice was still coming.)</li></ul><p>Next time: Kafka, event contracts, and a bug I put in the code deliberately so I could watch it lose data.</p><p><a href="https://medium.com/p/a34dcd79d658"><strong>Part:</strong> 2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11b0f1533e73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called a saga? #0: Why I built llm-mcp]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-a-saga-0-why-i-built-llm-mcp-d771dd586f84?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d771dd586f84</guid>
            <category><![CDATA[cdktf]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 00:03:57 GMT</pubDate>
            <atom:updated>2026-09-15T00:03:57.077Z</atom:updated>
            <content:encoded><![CDATA[<p>What happens to your money when the process that reserved it dies halfway through? I asked myself that question once at 2 a.m., and instead of going to sleep like a normal person, I spent two weeks building a project to find out.</p><p>This is the first post of a series. Each of the next seven posts covers one phase of the project, a day or two of my life, and at least one thing breaking on purpose. If you’re a Node.js developer who knows some Java and wants to get serious about Spring, Kafka and Kubernetes without reading twelve books first, or if you just enjoy stories about `<strong><em>kill -9</em></strong>`, you’re in the right place. Let’s begin!</p><h3>The thing</h3><p>The project is called <strong>llm-mcp</strong>. It’s a credit-based LLM job pipeline. A user sends a prompt and a model name. The system reserves some credits, runs the prompt against an LLM provider, stores the result, and charges the actual cost. If anything goes wrong, the reservation is released and the user keeps their credits. That’s the whole product. My father would not be impressed.</p><p>Happy path in one line:</p><pre><strong>POST /api/jobs → <em>JobCreated</em> → <em>CreditReserved</em> → LLM call → <em>LlmSucceeded</em> → <em>JobCompleted</em> → <em>CreditCaptured</em></strong></pre><p>Sad path in one line:</p><pre><strong>LLM fails or times out → <em>JobFailed</em> / <em>JobTimedOut</em> → <em>CreditReleased</em></strong></pre><p>Three services, three owners:</p><ul><li><strong>job-service</strong> owns the <strong><em>Job</em></strong>, its state machine, the public REST API and (later) an MCP server.</li><li><strong>credit-servic</strong>e owns the <em>CreditAccount</em> and the reservation: reserve, capture, release.</li><li><strong>llm-worker</strong> owns the LLM call, the provider adapters (<strong><em>fake</em></strong>, <strong><em>openai</em></strong>, <strong><em>gemini</em></strong>) and the resilience chain around them.</li></ul><p>Nobody calls anybody over HTTP. The only way services talk is events on Kafka, and the only shared code is a <strong><em>contracts</em></strong> module with the event definitions. Everything else in the project follows from that one rule. The moment you say “no shared database, no shared code, only events”, you <em>need</em> an outbox, an inbox and a saga. They aren’t fancy extras. They’re the bill you get for using the word “microservices”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irqE_EqYgafLUMBjTlmXhA.png" /><figcaption><strong><em>The happy path. Every arrow is an event on Kafka, not an HTTP call.</em></strong></figcaption></figure><h3>Why I did this to myself</h3><p>The first line of the project’s spec says: <em>“llm-mcp is a learning vehicle disguised as a product.”</em> I wrote that line, so I can’t pretend otherwise.</p><p>I’ve been writing Node.js and TypeScript backends for years. I know what an event loop is, I know what at-least-once delivery means, and I’ve argued about microservices in more meetings than I’d like to admit. I also know Java, somewhere around intermediate: the language, the collections, the basics of the JVM. What I didn’t have was real, hands-dirty experience with the stack around it: Spring Boot 4, JPA, Maven, Kafka from the producer’s side, plus a Kubernetes cluster I built myself instead of inheriting from someone who left the company.</p><p>And there’s a second reason. In a senior backend or system design interview, “I read about the outbox pattern” and “I built one, watched it lose events, then fixed it” are two very different sentences. I wanted the second one.</p><p>So I made myself some rules:</p><ol><li>The product has to really work, end to end. No diagrams of things that don’t exist.</li><li>Every important decision gets an Architecture Decision Record. I ended up with 28 of them, which is either impressive or a cry for help.</li><li>Every phase ends with a chaos exercise. Kill something, replay something, unplug something, write down what happened.</li><li>Nothing goes into the project from memory. Every version, every property name, every CLI flag gets checked in the official docs first and written into a file called `<a href="https://github.com/remidosol/llm-mcp/blob/main/docs/verified-versions.md">verified-versions.md</a>`.</li></ol><p>Rule four sounds like the most boring rule ever written. It saved me three times in the the first phase, two days at the keyboard. You’ll see in <a href="https://medium.com/p/11b0f1533e73">Part 1</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nuQOe--Nsv81xj4vmcAMbg.png" /><figcaption><strong><em>A learning vehicle disguised as a product.</em></strong></figcaption></figure><h3>One repo, four Maven modules (and why not the other options)</h3><p>Before writing any Java, I had to decide where the code lives. Monorepo or polyrepo? One fat Spring application or several?</p><p>I went with one git repository and one Maven reactor. If you come from Node.js, a Maven reactor is basically <strong>pnpm</strong> workspaces: the root <a href="https://github.com/remidosol/llm-mcp/blob/main/pom.xml"><strong><em>pom.xml</em></strong></a> lists the modules, one command builds everything, and `<strong><em>./mvnw -pl services/job-service -am verify`</em></strong> means “build this workspace and whatever it depends on”. The root pom holds version management only, a bit like a pnpm catalog, and zero code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtXo_Xd6KnQA-CHDxWuCpg.png" /><figcaption><strong><em>The reactor. The root pom knows versions, `contracts` knows events, the services know nothing about each other.</em></strong></figcaption></figure><p>Why not a polyrepo, the thing big companies do? Because I’m one person with a laptop and two weeks. Three repositories means three CI setups, three ways to forget a version bump, and nothing to learn from the split itself. The stuff I wanted to learn lives <em>*inside*</em> the services, not around them.</p><p>Why not one big application with nice packages? Because then the service boundaries are make-believe. It’s way too easy to import the credit repository from the job code “just this once, I’ll fix it later”. (Narrator: they did not fix it later.)</p><p>So the real question isn’t monorepo or not. It’s: how do you stop a monorepo from quietly becoming a distributed monolith? Three things, and all three are enforced by the build rather than by good intentions:</p><ul><li>Each service has its own database and its own database role. <strong><em>job-service</em></strong> physically can’t read the credit tables, even on a bad day.</li><li>The only shared module is <strong><em>contracts</em></strong>. There is <strong>no</strong> <em>common-utils</em>. I’ve seen how that movie ends.</li><li>ArchUnit tests run on every build. The domain package must be framework-free, the API layer may not touch infrastructure, and <strong><em>KafkaTemplate.send</em></strong> may exist in exactly one class. Break a boundary and the build goes red. Architecture lives in the build, not in a slide deck.</li></ul><p>One more detail I like: the repository is a monorepo for <strong><em>me</em></strong>, but every service ships from its own image and its own CI target. Independent deployability is a property of the pipeline, not of the folder structure.</p><h3>The map for the next seven posts</h3><p><a href="https://medium.com/p/11b0f1533e73"><strong>Part:</strong> 1</a><br><strong>Phase:</strong> Foundation<br><strong>What gets built:</strong> one service, schema, state machine, cache, real-database tests<br><strong>What gets broken on purpose:</strong> my Node.js habits</p><p><a href="https://medium.com/p/a34dcd79d658"><strong>Part:</strong> 2</a><br><strong>Phase:</strong> Kafka<br><strong>What gets built:</strong> event contracts, credit-service, inbox, dead letters<br><strong>What gets broken on purpose:</strong> a dual write, written on purpose</p><p><a href="https://medium.com/p/0c26c9d539a7"><strong>Part:</strong> 3</a><br><strong>Phase:</strong> Outbox<br><strong>What gets built:</strong> the transactional outbox, poller and Debezium<br><strong>What gets broken on purpose:</strong> Kafka, for six seconds</p><p><a href="https://medium.com/p/1900a1bb192d"><strong>Part:</strong> 4</a><br><strong>Phase:</strong> Saga<br><strong>What gets built:</strong> llm-worker, choreography, timeouts, late results<br><strong>What gets broken on purpose:</strong> the worker, with kill -9</p><p><a href="https://medium.com/p/ea2d0b09060a"><strong>Part:</strong> 5</a><br><strong>Phase:</strong> MCP, resilience<br><strong>What gets built:</strong> MCP server, token bucket, retry, breaker, API keys<br><strong>What gets broken on purpose:</strong> a fake OpenAI that returns 429</p><p><a href="https://medium.com/p/b3dc8f9fe2d3"><strong>Part:</strong> 6</a><br><strong>Phase:</strong> Kubernetes<br><strong>What gets built:</strong> kind, Strimzi, CloudNativePG, probes<br><strong>What gets broken on purpose:</strong> a readiness probe, a pod</p><p><a href="https://medium.com/p/83d99353424a"><strong>Part:</strong> 7</a><br><strong>Phase:</strong> Cloud, CI, tracing<br><strong>What gets built:</strong> CDK Terrain, Buck2, WIF, one trace across three services<br><strong>What gets broken on purpose:</strong> my budget (spoiler: I didn’t deploy)</p><p>Next time: Kafka, event contracts, and a bug I put in the code deliberately so I could watch it lose data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d771dd586f84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is this thing called Node.js?]]></title>
            <link>https://medium.com/@remidosol8/what-is-this-thing-called-node-js-73b1a8f91926?source=rss-ddedfd1fa7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/73b1a8f91926</guid>
            <category><![CDATA[v8-engine]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[İbrahim]]></dc:creator>
            <pubDate>Sat, 28 Dec 2024 03:47:02 GMT</pubDate>
            <atom:updated>2024-12-28T03:47:02.086Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What’s the deal with Node.js, anyway?</strong> If you’ve ever wondered how JavaScript managed to break out of the browser and handle everything from chat apps to e-commerce backends, you’re in the right place.</p><p>In this article, we’ll step through what makes Node.js so special, demystify how it uses V8, explore its event loop, and peek behind the scenes at asynchronous operations. Ready to dive deeper into the wonders of Node.js? Let’s begin!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLPuHt4NF9AkuT_fazQZ-Q.png" /></figure><p>Node.js is more than just a buzzword — it’s a technology that has transformed how we think about building modern applications. Since its debut in 2009, Node.js has taken JavaScript, once confined to the browser, and propelled it into the server-side world, making it a full-stack powerhouse.</p><p>At its core, Node.js is a lightweight, open-source runtime environment that runs JavaScript outside the browser using Google’s V8 engine. What sets Node.js apart is its event-driven, non-blocking architecture, which allows it to handle thousands of simultaneous connections with exceptional efficiency. This makes it ideal for real-time applications, APIs, and any task that demands high concurrency.</p><p>One of Node.js’s greatest strengths lies in its simplicity and scalability. By using a single-threaded event loop, it abstracts away the complexities of multithreading while enabling developers to manage asynchronous operations seamlessly. Combined with modern JavaScript features like promises and async/await, Node.js simplifies coding for scenarios traditionally fraught with complexity, such as handling I/O operations or scaling applications.</p><p>Its ecosystem is another standout feature. With npm, the world’s largest package repository, developers can tap into hundreds of thousands of reusable modules, streamlining development and fostering innovation. This modular approach has made Node.js a favorite for creating everything from lightweight APIs to enterprise-grade applications.</p><p>Big players like PayPal, Netflix, and Microsoft have embraced Node.js, proving its ability to scale from small projects to global systems. Whether you’re building your first server or architecting a microservices-based infrastructure, Node.js provides the tools and community to help you succeed.</p><p>So, what is this thing called Node.js? It’s not just a runtime — it’s a gateway to developing fast, scalable, and innovative applications, redefining the role of JavaScript in modern software development.</p><h3>What is the engine called V8?</h3><p>V8, Google’s JavaScript engine written in C++, is responsible for compiling and executing JavaScript code within a <strong>virtual machine</strong>. Anytime you see a webpage in Google Chrome dynamically updating content, like refreshing a news feed or modifying a list, that’s JavaScript in action, powered by V8. While Node.js efficiently handles I/O operations, it relies on the V8 runtime through its process object. As your application scales, understanding how to configure and optimize the V8 environment becomes increasingly important. By typing <em>node -h</em> into a console, something like the following will be displayed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5LOJfaLQL41HTJUzAvC4Fw.png" /><figcaption>A piece of the output of <strong>node -h</strong> command</figcaption></figure><p>We can see how a list of V8 options is accessible via the --<em>v8-options</em> flag.</p><p>The version of V8 used by your Node installation can be viewed by typing:</p><pre>node -e &quot;console.log(process.versions.v8)&quot;</pre><p>One particularly powerful V8 configuration option that Node.js integrates is --max-stack-size.</p><p>To better understand the flexibility Node.js developers now have in configuring a JavaScript runtime, let’s explore an example that pushes the limits of the system. Testing a system’s breaking points can reveal its constraints and behavior. Here’s a program designed to crash V8:</p><pre>var count = 0;<br>(function curse() {<br> console.log(++count);<br> curse();<br>})()</pre><p>This self-executing function recursively calls itself indefinitely, incrementing the call stack with each iteration. Eventually, the unchecked growth will cause the JavaScript runtime to crash, throwing a RangeError: Maximum call stack size exceeded.</p><p>This is where the purpose of the --max-stack-size option becomes evident. Its V8 equivalent, --stack_size, accepts a value in <strong>kilobytes</strong> (KB) to adjust the maximum call stack size and prevent such crashes.</p><p>By default, V8 allocates 700 MB of memory on 32-bit systems and 1400 MB on 64-bit systems. In more recent versions of V8, memory limits for 64-bit systems are no longer enforced by V8 itself, theoretically removing any hard limits. However, the actual ceiling depends on the operating system, as it controls how much memory a process can consume, making the precise limit system-dependent.</p><blockquote>JavaScript is evolving from its single-threaded nature into a language capable of multi-threading. For instance, the <strong><em>Atomics</em></strong> object introduces tools for coordinating communication between threads, while <strong><em>SharedArrayBuffer</em></strong> instances allow data to be read and written across threads. However, as of now, multithreaded JavaScript hasn’t gained widespread adoption within the community. Although JavaScript today supports multithreading, the language and its ecosystem are still largely rooted in a single-threaded paradigm.</blockquote><p>In browser-based programming, we write instructions that execute sequentially, one at a time, without parallel execution. However, this approach doesn’t work well for user interfaces, as users expect responsive interactions without delays caused by slow operations like network or file access. To handle this, browsers rely on events. For example, when you click a button, an event is triggered, and a pre-defined function is executed. This event-driven model helps avoid common problems in threaded programming, such as resource deadlocks and race conditions.</p><h3>What is the thing called Non-Blocking I/O?</h3><p>I/O operations like disk and network access tend to be relatively slow, so it’s important that the runtime doesn’t block business logic while waiting for files to be read or messages to be sent over the network. To address this, Node employs three key strategies: events, asynchronous APIs, and nonblocking I/O. From a Node developer’s perspective, nonblocking I/O ensures that your program can request a network resource and continue performing other tasks. Once the network operation completes, a callback is triggered to handle the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*riXVODt7zRTL__JHJSUrJw.png" /><figcaption>Asynchronous and nonblocking components in a Node application</figcaption></figure><p>Let’s imagine a typical Node.js web application using the Express framework to manage an order workflow for an online shop. In this scenario, browsers send requests to purchase a product, and the application performs several tasks: it checks stock inventory, registers the user, emails a receipt, and sends back a JSON response. At the same time, other processes are happening too, such as sending the email receipt and updating the database with the user’s details and order information. Although the code is straightforward, imperative JavaScript, the runtime operates concurrently thanks to its use of nonblocking I/O.</p><p>For instance, accessing the database over the network is a nonblocking operation in Node.js. This is made possible by a library called <em>libuv</em>, which provides access to the operating system’s nonblocking network calls. Libuv handles this differently on Linux, macOS, and Windows, but as a developer, you only interact with your JavaScript database library. For example, when writing code like db.insert(query, err =&gt; {}), Node is performing highly optimized, nonblocking networking behind the scenes.</p><p>Disk access in Node.js works in a slightly different way compared to network access. For example, when generating an email receipt and reading the email template from the disk, <em>libuv</em> uses a <strong>thread pool</strong> to simulate the behavior of a non-blocking call. Managing a thread pool can be complex and tedious, but for developers, it’s simplified into something more intuitive, like writing email.send(&#39;template.ejs&#39;, (err, html) =&gt; {}).</p><p>The real power of using asynchronous APIs combined with nonblocking I/O lies in Node.js’s ability to continue executing other tasks while waiting for these slower operations to complete. Even with a single-threaded, single-process Node.js application, it’s capable of handling thousands of concurrent connections. This efficiency is achieved by the event loop, which is key to understanding how Node operates.</p><h3>What is the thing called Event Loop?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZuPWyMkGZz4wEOutCV59VQ.png" /></figure><p>As the name suggests, the event loop operates in a continuous loop. At its core, it manages a queue of events, triggering callbacks to progress the application’s execution. However, as simple as it sounds, the actual implementation is far more intricate.</p><p>The event loop is responsible for executing callbacks when specific I/O events occur, such as receiving a message on a socket, detecting a file change on disk, or a setTimeout() callback being ready to execute. At a deeper level, the operating system notifies the program that an event has occurred. This triggers the libuv library within Node.js to handle the event and determine the next steps. If necessary, the event progresses through the Node.js API, eventually invoking a callback in the application code. Essentially, the event loop acts as a <strong>bridge</strong>, allowing lower-level C++ events to trigger JavaScript code execution.</p><pre>   ┌───────────────────────────┐<br>┌─&gt;│           timers          │<br>│  └─────────────┬─────────────┘<br>│  ┌─────────────┴─────────────┐<br>│  │     pending callbacks     │<br>│  └─────────────┬─────────────┘<br>│  ┌─────────────┴─────────────┐<br>│  │       idle, prepare       │<br>│  └─────────────┬─────────────┘      ┌───────────────┐<br>│  ┌─────────────┴─────────────┐      │   incoming:   │<br>│  │           poll            │&lt;─────┤  connections, │<br>│  └─────────────┬─────────────┘      │   data, etc.  │<br>│  ┌─────────────┴─────────────┐      └───────────────┘<br>│  │           check           │<br>│  └─────────────┬─────────────┘<br>│  ┌─────────────┴─────────────┐<br>└──┤      close callbacks      │<br>   └───────────────────────────┘</pre><p>The event loop in Node.js operates in multiple phases, each serving a specific purpose. While some phases handle internal Node.js operations, others are directly relevant to application code. Each phase manages a queue of callbacks scheduled to execute, depending on how they are utilized in the application. Here’s an overview of the key phases:</p><ul><li><strong>Poll</strong>: This phase handles I/O-related callbacks and is where most application code executes. When your main code begins running, it typically starts in this phase.</li><li><strong>Check</strong>: Callbacks triggered by setImmediate() are executed in this phase.</li><li><strong>Close</strong>: This phase handles callbacks associated with EventEmitter close events. For instance, when a net.Server TCP server closes, it emits a close event, which runs a callback in this phase.</li><li><strong>Timers</strong>: Callbacks scheduled using setTimeout() and setInterval() are executed in this phase.</li><li><strong>Pending</strong>: This phase processes special system events, such as when a net.Socket TCP socket encounters an ECONNREFUSED error.</li></ul><p>Each phase ensures the orderly execution of tasks, enabling Node.js to manage asynchronous operations effectively.</p><p>The event loop introduces additional complexity with two special <strong>microtask queues</strong>, which can have callbacks added during the execution of a phase:</p><ol><li><strong>Next Tick Microtask Queue</strong>: Handles callbacks registered with process.nextTick(). These callbacks take the highest priority and are executed before anything else.</li><li><strong>Promise Microtask Queue</strong>: Manages callbacks for resolved or rejected promises. These run after callbacks in the next tick queue but still take precedence over the normal phase queue.</li></ol><blockquote>Event loop executes tasks in process.nextTick queue first, and then executes promises microtask queue, and then executes macrotask queue.</blockquote><p>When the application begins execution, the event loop starts and processes phases sequentially. Node.js assigns callbacks to the appropriate queues as the program runs. During a phase, the event loop executes all the callbacks in that phase’s queue. Once finished, it moves to the next phase.</p><p>In the <strong>poll phase</strong>, the event loop focuses on managing I/O-related tasks. If the poll queue contains callbacks, they are executed synchronously until the queue is <em>cleared</em> or a system-defined <em>limit</em> is reached. However, if the poll queue is <strong>empty</strong>, the behavior depends on other scheduled tasks:</p><ul><li>If setImmediate() callbacks are <strong>waiting</strong>, the event loop moves directly to the <strong>check phase</strong> to handle them.</li><li>If <strong>no</strong> setImmediate() callbacks exist, the event loop <strong>pauses</strong> in the <strong>poll phase</strong>, waiting for <strong><em>new events</em></strong> or <strong><em>I/O tasks</em></strong> to arrive, which it processes immediately.</li></ul><p>Once the poll queue is <strong>empty</strong>, the event loop checks for <strong>timers</strong> with expired thresholds. If any are ready, it circles back to the <strong>timers phase</strong> to execute their <em>associated callbacks</em> before continuing through the remaining phases.</p><pre>const fs = require(&#39;fs&#39;);<br>const EventEmitter = require(&#39;events&#39;).EventEmitter;<br><br>let pos = 0;<br><br>const messenger = new EventEmitter();<br><br>messenger.on(&quot;message&quot;, function(msg) {<br> console.log(++pos + &quot; EVENT: &quot; + msg);<br>});<br><br>// (A) FIRST CONSOLE<br>console.log(++pos + &quot; FIRST CONSOLE (A)&quot;);<br><br>// (B) NEXTTICK<br>process.nextTick(function() {<br> console.log(++pos + &quot; NEXTTICK (B)&quot;)<br>})<br><br>// (C) QUICK TIMER<br>setTimeout(function() {<br> console.log(++pos + &quot; QUICK TIMER (C)&quot;)<br>}, 0)<br><br>// (D) PROMISE RESOLVE<br>Promise.resolve().then(() =&gt; console.log(++pos + &quot; PROMISE RESOLVE (D)&quot;));<br><br>// (E) LONG TIMER<br>setTimeout(function() {<br> console.log(++pos + &quot; LONG TIMER (E)&quot;)<br>}, 10)<br><br>// (F) IMMEDIATE<br>setImmediate(function() {<br> console.log(++pos + &quot; IMMEDIATE (F)&quot;)<br>})<br><br>// (G) MESSAGE HELLO!<br>messenger.emit(&quot;message&quot;, &quot;MESSAGE (G)&quot;);<br><br>// (H) FIRST STAT<br>fs.stat(__filename, function() {<br> console.log(++pos + &quot; FIRST STAT (H)&quot;);<br>});<br><br>// READ FILE<br>fs.readFile(__filename, () =&gt; {<br>  // (I) READ FILE CONSOLE<br> console.log(++pos + &quot; READ FILE CONSOLE (I)&quot;);<br> <br>  // (J) READ FILE TIMER<br> setTimeout(() =&gt; console.log(++pos + &quot; READ FILE TIMER (J)&quot;), 0);<br> <br>  // (K) READ FILE IMMEDIATE<br> setImmediate(() =&gt; console.log(++pos + &quot; READ FILE IMMEDIATE (K)&quot;));<br> <br>  // (L) READ FILE NEXTTICK<br> process.nextTick(() =&gt; console.log(++pos + &quot; READ FILE NEXTTICK (L)&quot;));<br>});<br><br>// (M) LAST STAT<br>fs.stat(__filename, function() {<br> console.log(++pos + &quot; LAST STAT (M)&quot;);<br>});<br><br>// (N) LAST CONSOLE<br>console.log(++pos + &quot; LAST CONSOLE (N)&quot;);</pre><p>The execution order of the code above is a great demonstration of how Node.js handles asynchronous operations with its event loop. Here’s a phase-by-phase breakdown with some nuanced details:</p><ol><li><strong>Synchronous Phase: </strong>JavaScript starts by executing all synchronous code in order. This includes:</li></ol><ul><li>(A) First console log.</li><li>(G) EventEmitter&#39;s synchronous emit.</li><li>(N) Last console log.</li></ul><p><strong>2. Microtasks: </strong>Microtasks take precedence over other phases.</p><ul><li>(B) process.nextTick is executed first, as it has the highest priority among microtasks.</li><li>(D) Resolved promises follow process.nextTick, ensuring PROMISE RESOLVE comes next.</li></ul><p><strong>3. Timers Phase</strong></p><ul><li>(C) A zero-delay setTimeout runs after microtasks, enqueuing and executing QUICK TIMER.</li></ul><p><strong>4. Poll Phase (I/O)</strong></p><ul><li>(H) and (M) correspond to fs.stat, processed in the poll phase as I/O callbacks.</li></ul><p><strong>5. Check Phase</strong></p><ul><li>(F) setImmediate gets its turn, executing after I/O callbacks from the poll phase.</li></ul><p><strong>6. Nested Callbacks</strong><br>Once fs.readFile completes, its nested callbacks are executed. Notice how these maintain the same event loop rules:</p><ul><li>(I) Runs synchronously after readFile completion.</li><li>(L) A process.nextTick nested callback executes immediately.</li><li>(K) setImmediate follows, as it&#39;s in the check phase. (setImmediate() will always be executed before <em>any timers</em> if scheduled <strong>within</strong> an <strong>I/O cycle</strong>, independently of how many timers are present.)</li><li>(J) A nested setTimeout runs afterward.</li></ul><p><strong>7. Timers Phase (Delayed)</strong></p><ul><li>(E) The delayed setTimeout(10) finally gets processed after everything else.</li></ul><p>The output of is program is:</p><pre>1 FIRST CONSOLE (A)<br>2 EVENT: MESSAGE (G)<br>3 LAST CONSOLE (N)<br>4 NEXTTICK (B)<br>5 PROMISE RESOLVE (D)<br>6 QUICK TIMER (C)<br>7 FIRST STAT (H)<br>8 LAST STAT (M)<br>9 IMMEDIATE (F)<br>10 READ FILE CONSOLE (I)<br>11 READ FILE NEXTTICK (L)<br>12 READ FILE IMMEDIATE (K)<br>13 READ FILE TIMER (J)<br>14 LONG TIMER (E)</pre><h3>Conclusion</h3><p>So, what did we learn here today? Besides finding out that Node.js can handle more concurrent connections than your favorite streaming service handles cat videos, we discovered it’s powered by a zippy V8 engine that basically turns JavaScript into a roadster at the racetrack. Of course, just like any high-performance car, Node.js comes with a few useful flags (looking at you, --max-stack-size) to keep your call stack from exploding in a <em>beautiful</em> ball of recursion flames.</p><p>But the real magic here is how Node.js uses its event loop and <strong>libuv</strong> to juggle I/O tasks — simultaneously managing everything from serving data to emailing receipts, all in a single-threaded environment that never seems to break a sweat. It’s like having one super-employee who can keep a thousand tasks in the air without dropping a single one.</p><p>And this is just the beginning. In our next article, we’ll dive into Node.js <strong>Streams</strong> and explore how Node can handle data like a professional juggler. We’ll also look into <strong>HTTP</strong>, <strong>WebSockets</strong>, and <strong>gRPC</strong> protocols — revealing how each of these technologies can make real-time communication and data handling even more delightful.</p><p>Ready to take your Node.js skills to the next level? Stick around — the road ahead is going to be a thrilling ride, and we’ve got plenty more tricks up our Node-sleeve!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73b1a8f91926" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>