Skip to content
PodSubs
ShowsPeopleGuestsJobsNewsEvents
More
BlogPodCred
Menu
ShowsPeopleGuestsJobsNewsEventsBlogPodCredNetworksSign in
Join nowSign in
  • Shows
  • People
  • Jobs
  • News
  • More
    • Guests
    • Events
    • Blog
    • PodCred
    • Networks
    Join nowSign in

Coordinated with Fredrik

Coordinated with Fredrik artwork

NATS as the Nervous System of the Grid

Feb 28, 202640 minAudio
ShareXLinkedInFacebookWhatsAppEmail

In this special episode of Coordinated with Fredrik, we went deep - not at the strategy layer, not at the founder layer, but at the socket level. This was a strict engineering teardown of a single question: Can NATS become the autonomic nervous system of Sourceful Energy? What follows is the architectural synthesis. The Real Problem We’re Solving At Sourceful, we are not just operating a backend. We are coordinating: * High-throughput mobile app traffic * A growing mesh of backend microservices * Massive telemetry streams from distributed energy assets * Smart meters * EV chargers * Solar arrays in remote geographies * Wind turbines behind unstable uplinks This is not a traditional cloud-native architecture. It is cloud + edge + unreliable networks + financial correctness. That requires more than horizontal scaling. It requires: * Isolation of failure domains * Backpressure awareness * Autonomous routing * Dynamic topology adaptation * Edge survivability This is where NATS becomes interesting. The 15 MB Binary That Changes the Conversation NATS runs as a single static Go binary of roughly 15 MB. A single node can handle 15-18 million messages per second. That sounds unrealistic until you understand the engineering choices: Concurrency Model * Lightweight goroutines * User-space scheduling * Massive TCP connection density Memory Discipline * Zero-allocation parsing * Pointer passing instead of object churn * Minimal garbage collection pauses Routing Philosophy * Pure in-memory message routing * Disk I/O only when explicitly requested NATS is not a heavyweight enterprise broker. It is a highly optimized, high-throughput routing engine. Selfish Optimization: Protect the System First One of the most controversial ideas in NATS is “selfish optimization.” If a downstream consumer slows down: * NATS does not buffer indefinitely * NATS does not slow producers * NATS drops the connection From a traditional enterprise mindset, that sounds aggressive. But in distributed energy systems, it is correct. If the router collapses: * Telemetry stops * Control signals stop * Billing APIs stop * The entire system fails Protecting the health of the transport layer is non-negotiable. The whole must survive even if individual services fail. Core NATS vs JetStream NATS separates transient routing from durability. Core NATS * In-memory * Fire-and-forget * Ultra-low latency * No persistence If no subscriber exists, the message is dropped. Use this for: * Real-time telemetry * State queries * Fast internal RPC JetStream * Durable streams * Raft-based replication * Replayable consumers * At-least-once / exactly-once semantics Use this for: * Billing events * Immutable records * Financial correctness The key principle: Persistence is opt-in. You only pay for disk I/O when the workload requires it. Raft Without the Bottleneck Most distributed streaming systems rely on a single global consensus group. JetStream does something different: * One meta-consensus group for cluster metadata * Independent Raft groups per stream * Even per consumer If you run 5,000 streams, you run 5,000 independent consensus groups. Why does that not collapse under overhead? Because: * Each Raft group runs as a lightweight goroutine * Heartbeats are batched * Streams are isolated A spike in one stream does not block the others. This is horizontal scalability at the consensus layer. Subject-Based Routing Instead of IP-Based Thinking NATS routes by subject strings, not by IP addresses. Example: telemetry.eu.germany.meter80492 Routing is powered by an optimized radix trie. This means: * No regex matching * No linear scans * Logarithmic routing complexity Subject hierarchies become your semantic network. Developers stop thinking about: * Hostnames * Ports * DNS * Reverse proxies They express interest in data. The infrastructure routes it. Request-Reply Without HTTP NATS supports request-reply patterns without point-to-point connections. Mechanically: * The requester generates a temporary reply subject * Publishes a message including that subject * A service processes and replies to that subject * The first response wins To developers, it feels synchronous. Under the hood, it is fully asynchronous and multiplexed. Queue groups provide built-in distributed load balancing. This eliminates internal service meshes and east-west load balancers for microservice communication. Public ingress still requires API gateways. Internal routing becomes dramatically simpler. Global Scaling with Superclusters Inside a region, NATS uses a full mesh cluster. Across regions, it uses superclusters connected by gateways. Gateways operate in interest-only mode. If Europe is not subscribing to US telemetry: * No bytes cross the Atlantic. The moment interest appears: * Flow begins automatically. This prevents blind data mirroring and reduces egress costs dramatically. Leaf Nodes: Edge Autonomy Leaf nodes are where NATS becomes transformative for energy infrastructure. A leaf node: * Runs locally on edge hardware * Initiates an outbound TLS connection to the core * Requires no inbound firewall rules * Multiplexes all traffic over a single connection If connectivity drops: * Local JetStream buffers telemetry * Local control systems continue functioning * No data is lost When connectivity restores: * The stream synchronizes automatically * Consumers resume from correct offsets This enables: Autonomous edge during disconnection. Seamless federation when connected. For EV chargers, solar arrays, and wind turbines, this is critical. Decentralized Security at Scale Traditional brokers rely on centralized authentication. That becomes a bottleneck at scale. NATS uses: * ED25519 keypairs * JWT-based trust hierarchy * Operator → Account → User model Authentication becomes pure cryptographic verification. No database lookups. No external latency. No central auth bottleneck. Permissions are embedded in JWT claims: * Publish rights * Subscribe rights * Data limits Revocation can be pushed in real time without cluster restarts. For enterprises tied to Okta or LDAP, auth callouts bridge existing identity systems into decentralized JWT issuance. This allows compliance without sacrificing performance. Kafka, RabbitMQ, MQTT - Where NATS Fits Kafka Designed for: * Durable append-only logs * Analytics pipelines * Data lakes Strength: * Historical retention Tradeoff: * Partition-bound scaling * Consumer rebalancing pauses * Operational overhead NATS: * Dynamic routing * Elastic worker scaling * Lower latency for microservices RabbitMQ Designed for: * Complex exchange-based routing Tradeoff: * Higher operational fragility under partitions * Cluster state complexity NATS: * Simpler subject routing * Gossip for cluster sync * Raft-backed durability MQTT Best for: * Constrained IoT devices NATS does not replace MQTT. It embeds an MQTT broker. MQTT topics are mapped directly to NATS subjects internally. This creates a unified backbone: * Edge devices speak MQTT * Backend services speak NATS * No external translation layer required The Paradigm Shift For decades, distributed systems have been built around: * IP addresses * DNS names * Blocking HTTP calls * Explicit service discovery NATS introduces a different idea: Express interest in a semantic subject. Let an autonomic system route it dynamically. In a world of: * Real-time AI inference * Autonomous energy assets * Fluid containerized workloads * Distributed edge computing IP-based thinking becomes friction. Subject-based thinking becomes leverage. What This Means for Sourceful Adopting NATS is not swapping a queue. It is: * Flattening internal service meshes * Eliminating east-west load balancers * Moving complexity into autonomic infrastructure * Enabling edge-first resilience * Protecting system health by design * Running a global coordination backbone on a single optimized binary The goal is operational simplicity. Push complexity into the transport layer. Free engineers to focus on energy optimization logic. If we get this right: The infrastructure becomes invisible. And the grid becomes programmable. This is a public episode. If you would like to discuss this with other subscribers or get access to bonus episodes, visit frahlg.substack.com

Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.

Transcript

From the show. Tap a time to play from there.

SPEAKER_01Welcome to this custom deep dive on the Coordinated with Frederick show. Today, we're opening up a highly specialized session, and I want to speak directly to you, the senior engineering team at Sourceful Energy.

SPEAKER_00Yeah, it's great to be jumping into this with you all.

SPEAKER_01We know the exact architectural hurdles you're facing right now. You're tasked with balancing high throughput mobile app traffic, an expanding web of back end microservices and, you know, massive relentless streams of telemetry from all your remote energy assets.

SPEAKER_00Right. We're talking about the smart meters, the remote solar arrays in the middle of nowhere, offshore wind turbines, the whole electric vehicle charging network.

SPEAKER_01Exactly. And that specific blend of cloud-native backend and highly distributed edge infrastructure, it requires an architecture that doesn't just scale up or out, but topologies that actually adapt dynamically to network instability. Because the operational reality for you at Sourceful Energy is that you are dealing

SPEAKER_00with distinct failure domains constantly. A cellular drop at a solar array in the desert, it simply cannot trigger a cascading failure that impacts the billing APIs in your central cloud. You need infrastructure that inherently understands isolation, back pressure, and autonomous routing.

SPEAKER_01Which brings us to the core mission of today's deep dive. We are going to completely deconstruct NATS, the neural autonomic transport system.

SPEAKER_00And we're going to do this at a strict socket level engineering depth.

SPEAKER_01Right. Our goal here is to provide a comprehensive pedagogical framework for exactly how the NATS binary operates under the hood and how you can exploit its design to maximize performance across your entire stack. We've synthesized a massive stack of source material for this.

SPEAKER_00We pulled from the official CNCF technical documentation, exhaustive architectural teardowns, comparative benchmarks, and some really deep dive interviews with Nats creator Derek Collison.

SPEAKER_01Yeah. We're bypassing the standard marketing bullet points today. We're looking at the actual socket level mechanics, the memory management, the consensus algorithms Nats employs.

SPEAKER_00Because the claim we are investigating today is substantial. The claim that NATS is not just a message broker, but a decentralized nervous system capable of eradicating massive amounts of tech stack bloat.

SPEAKER_01Meaning eliminating the need for service meshes, internal load balancers, and complex reverse proxies. So let's just, let's address the elephant in the room right away. Because this is the data point that immediately demands scrutiny. The sources indicate that NATS is deployed as a single static Go binary.

SPEAKER_00Right. Just one binary.

SPEAKER_01And it's roughly 15 megabytes.

SPEAKER_00Divertake, yeah. Yet a single server node can push between 15 and 18 million messages per second. It sounds absurd when you first hear it.

SPEAKER_01It really does.

SPEAKER_00Yes. In a world where enterprise Java brokers require massive heap allocations and dedicated zookeeper clusters just to handle a fraction of that throughput, how is a 15 megabyte binary achieving sub-millisecond latency at that scale?

SPEAKER_01To understand that, I think we need to look at the genesis of the project and the architectural pivot it made early on. Well, the architecture is a direct reflection of Derek Collison's background.

SPEAKER_00Before building Nats, he spent a quarter century building some of the most complex enterprise messaging systems in the world, specifically TPCL Rendezvous and the enterprise messaging system.

SPEAKER_01Right. These were the heavyweights.

SPEAKER_00Oh, absolutely. These were the highly rigid, heavily centralized brokers running Wall Street trading floors. And Collison often refers to having scars on his back from those legacy systems.

SPEAKER_01Because they were fragile.

SPEAKER_00They were powerful, but they were incredibly... incredibly fragile under edge caseloads. They required constant operational babysitting, really complex JVM tuning, and they frequently just buckled under their own weight when pushed into severe back pressure scenarios.

SPEAKER_01So when he set out to build NATS in 2010...

SPEAKER_00Which was initially to serve as the control plane for Cloud Foundry, by the way.

SPEAKER_01Right, right. The mandate was extreme operational simplicity and absolute resilience. But the interesting technical pivot in the sources is the language transition. Because NATS wasn't originally written in Go, was it?

SPEAKER_00No, it was originally written in Ruby.

SPEAKER_01Which is wild.

SPEAKER_00It is. Because eventually they rewrote the entire control plane and data plane in Go. For a system whose entire existence is based on highly concurrent IO multiplexing, being trapped in Ruby seems like, well, an architectural death sentence.

SPEAKER_01Because of the global interpreter lock, the GIL.

SPEAKER_00Exactly. The GIL fundamentally prevents multiple threads from executing Ruby code simultaneously. If your entire system is designed to route millions of discrete messages across hundreds of thousands of concurrent TCP connections, a GIL is a hard, unavoidable bottleneck.

SPEAKER_01You literally just can't parallelize the socket reads.

SPEAKER_00You can't. So the transition to Go was the absolute inflection point for NATS. Go's concurrency model, utilizing Goratine's and its end-to-end scheduler, it perfectly aligns with the requirements of a high-throughput router.

SPEAKER_01Let's dig into that execution model for a second. We know goroutines are lightweight, but how does the NATS server specifically structure them to avoid CPU context switching overhead, especially when handling, say, 100,000 active smart meter connections at sourceful? Okay, so NATS assigns a specific set of goroutines to every single client connection.

SPEAKER_00Typically, there is one goroutine strictly dedicated to reading from the TCP socket and parsing the incoming byte stream, and another dedicated entirely to flushing data back out to that socket.

SPEAKER_01So two per connection.

SPEAKER_00Generally, yes. And because goroutines only consume a few kilobytes of stack memory initially. As opposed to traditional OS threads, which might demand a full megabyte or more. Exactly. So NATs can maintain hundreds of thousands of concurrent connections entirely in user space. The Go runtime scheduler then effortlessly multiplexes those user space goroutines across the available hardware CPU threads.

SPEAKER_01So the OS isn't constantly context switching.

SPEAKER_00Right. And NATS goes a step further by utilizing highly optimized zero allocation byte parsing. It completely avoids creating new objects in memory for every message, which drastically reduces garbage collection pauses.

SPEAKER_01So it's just passing pointers around.

SPEAKER_00Yes. That is how you get 18 million messages a second out of a 15 megabyte binary. It is essentially a pure frictionless conduit to the underlying network interface. That brings up the philosophy behind the name, neural autonomic transport system.

SPEAKER_01We're talking biology here, not just computer science.

SPEAKER_00Yeah, autonomic.

SPEAKER_01Right. The autonomic nervous system in the human body handles heart rate and respiration without conscious input, and it prioritizes the survival of the core organism above all else. The sources mention a design principle in Nats called selfish optimization.

SPEAKER_00Which is fascinating. It seems highly controversial from a traditional enterprise architecture standpoint.

SPEAKER_01I mean, if a downstream consumer is struggling, traditional brokers try to buffer the data, slow down the producers, or essentially bend over backward to ensure that struggling service gets its data, Nats does the exact opposite.

SPEAKER_00It is a radical departure from traditional broker design. NATS is fundamentally designed to protect the health of the central server at all costs. Collison uses an analogy of a faulty blender.

SPEAKER_01The broken blender.

SPEAKER_00Right. If you plug a broken blender into a wall socket and it shorts out, you do not want the entire city's power grid to adjust its voltage or crash trying to accommodate it. You want the circuit breaker to trip immediately, isolating the faulty appliance and protecting the grid.

SPEAKER_01I understand the analogy, but let's apply this to a real scenario you guys might face at Sourceful Energy. Let's say one of the back-end microservices responsible for persisting daily billing aggregates suffers a database deadlock. It completely stops reading from its TCP socket. Okay. NATS is trying to push data to it, but the client's TCP receive window fills up. Are you saying NATS just aggressively severs the connection? Isn't data loss unacceptable? Yes.

SPEAKER_00It's a matter of systemic triage. When that client's socket buffer saturates, NATS actively monitors the back pressure and designates that connection as a slow consumer. If it hits a predefined threshold, NATS will autonomously and ruthlessly drop the connection. Wow. From an architectural standpoint, yes, that specific client misses real-time messages. But consider the alternative. If NATS pauses to buffer everything in memory for that deadlocked billing service, the NATS server's memory heap will explode.

SPEAKER_01Which leads to garbage collection hell. It will trigger massive garbage collection pauses, or worse, an out-of-memory crash.

SPEAKER_00If the NATS server goes down, the real-time telemetry from every wind turbine, the control signals to every EV charger, and the API responses for every mobile app go down with it.

SPEAKER_01You lose the whole nervous system.

SPEAKER_00Right. Selfish optimization ensures dial tone reliability for the broader grid. The health of the whole outweighs the health of the individual component.

SPEAKER_01I see the necessity. But as an SRE, deliberately dropping data is a tough pill to swallow, which I think perfectly transitions into how the architecture is actually divided to solve that exact problem. Because NATS operates on a two-tiered architecture, cornets and gesture, what we just described.

SPEAKER_00The ruthless fire and prey at most wants delivery mechanism.

SPEAKER_01Yes, that is cornets.

SPEAKER_00Precisely. CoreNATS is a pure in-memory message router. It offers absolutely zero built-in persistence. If a microservice publishes a message and there are no active subscribers registered in the writing table at that exact microsecond, the message is dropped instantly. Gone. Gone. It is optimized for the lowest possible latency and the highest possible throughput. It strips away all the overhead of disk IO, acknowledgement tracking, and state management.

SPEAKER_01But sourceful energy has workloads that explicitly require durability. I mean, if an EV charger completes a transaction, that billing event must be captured. If CoreNATS drops it because of a network blip, we have a severe financial reconciliation issue. And that is exactly why Jetstream was integrated directly into the binary.

SPEAKER_00Jetstream is the modern persistence engine for NATs. It replaces the older, deprecated stand system.

SPEAKER_01Right, NAT streaming.

SPEAKER_00Exactly. Jetstream introduces the concepts of strings in consumers. A stream durably writes messages to disk, and a consumer provides a stateful, replayable view into that stream. This layer provides your required at least once, and exactly once, delivery semantics.

SPEAKER_01So it's baked into the same 15 megabyte binary?

SPEAKER_00Yes. NATS operates on a principle of opt-in complexity. By default, the system is lightweight and transient. You only incur the latency penalty and operational cost of disk I.O. when a specific workload explicitly demands it.

SPEAKER_01Okay, let's pop the hood on Jetstream then. High availability persistence usually means complex consensus algorithms. The sources confirm Jetstream uses Raft. But traditional systems like Zookeeper or Kafka's Craft use a single global consensus group.

SPEAKER_00Which becomes a massive scaling bottleneck as partition counts rise.

SPEAKER_01Exactly. Because every state change has to go through that one global bottleneck.

SPEAKER_00Yeah.

SPEAKER_01How does Jetstream implement RAF differently to avoid that exact issue?

SPEAKER_00That is where Jetstream's architecture is quite brilliant. It does not use a single monolithic RAF group. It utilizes a meta-raft group that is strictly responsible for cluster-wide API leadership and stream placement decisions.

SPEAKER_01Just the metadata.

SPEAKER_00Right. However, for the actual data plane, Jetstream spins up an independent parallel raft consensus group for every single stream, and even for every single consumer.

SPEAKER_01Hold on. Let me map this out. If Sourceful Energy deploys 5,000 durable streams for different regional smart meter aggregates, we are running 5,000 distinct Raft consensus groups simultaneously.

SPEAKER_00Yes. Doesn't the heartbeat network overhead alone cause massive socket exhaustion and CPU thrashing?

SPEAKER_01Raft is chatty.

SPEAKER_00In a traditional threading model, absolutely, it would be catastrophic. But because NATS is built on Go, those 5,000 raft groups are just lightweight gory teens.

SPEAKER_01Ah, right. Back to the gory teens.

SPEAKER_00Furthermore, NATS heavily optimizes the raft implementation itself. It batches heartbeats and piggybacks them onto existing data payloads whenever possible to reduce network chatter. That's smart. This per-stream raft architecture is what allows Jetstream to scale horizontally almost indefinitely. If a single stream experiences a massive spike in throughput, its raft election and log replication do not block or interfere with the other 4,999 streams in the cluster.

SPEAKER_01It's completely isolated at the storage layer. Let's walk through a failure state because that's what SREs care about at the end of the day. Say we have a five-node NATS cluster running Jetstream distributed across three availability zones. A network partition occurs, completely isolating two nodes from the other three. How does Jetstream handle the split-brain scenario? Because of the strict raft implementation, split-brain is mathematically prevented.

SPEAKER_00The partition with the three nodes maintains a quorum. That's a majority of the five-node cluster. The streams on those three nodes will seamlessly elect new leaders if necessary and continue accepting writes.

SPEAKER_01Business as usual for the majority.

SPEAKER_00Right. But the two isolated nodes instantly lose quorum. They will refuse to accept any new publish acknowledgements for durable streams, protecting the system from conflicting rights.

SPEAKER_01They just reject the traffic.

SPEAKER_00Yes. Once the network partition heals, the two isolated nodes reconnect, realize they are behind the current raft term, and automatically catch up their local disk logs via stream replication from the quorum leaders.

SPEAKER_01That is incredibly robust. And what's fascinating in the documentation is that because NATS built this highly optimized replicated storage engine for Jetstream, they realized they could expose that same storage primitive in different ways. They built a key value store and an object store directly into the NATS binary, utilizing the exact same raft back streams.

SPEAKER_00It is a massive operational advantage. NATS key value stores support time-to-live expirations, historical versioning, and atomic watch capabilities. The object store handles chunked file transfers, reassembling large payloads automatically.

SPEAKER_01So if I'm an architect at Sourceful, I don't necessarily need to deploy and manage a separate Redis cluster for distributed caching or spin up a Minio cluster for basic blob storage. I could just use the NATS infrastructure that is already handling my microservice messaging.

SPEAKER_00Exactly. You get all that out of the box. But there is a crucial architectural philosophy to keep in mind here, one that Derek Collison strongly emphasizes. What's that? While Jetstream is powerful, you should default to cornets whenever possible. State is the enemy of resilience.

SPEAKER_01State is the enemy. Systems that rely purely on historical data replays often suffer from thundering herd problems.

SPEAKER_00When a crashed service wakes up and tries to process a massive backlog of persistent messages all at once, it can easily crush downstream databases or trigger cascading failures.

SPEAKER_01I've seen that happen. The recovery actually kills the system. Collison notes that the most resilient systems he has built over 30 years are

SPEAKER_00strictly stateless, real time and self-correcting. If a mobile app wants the current status of an EV charger, it shouldn't query a historical database. It should ping the charger over core NATs and get a real time response. Only use Jetstream when the business logic absolutely mandates an immutable historical ledger. That distinction between stateful ledgers and real-time routing leads us perfectly

SPEAKER_01to the communication patterns. How do developers actually route data through this system? Because this is where the daily lives of the sourceful energy backend developers will radically change. We are talking about eradicating layers of tech stack bloat by shifting from IP-based routing to subject-based routing. The fundamental paradigm shift is that NATS has no concept of IP addresses,

SPEAKER_00host names, or ports in its routing logic. You do not send a message to a destination. You publish a message to a subject.

SPEAKER_01A subject.

SPEAKER_00A subject is simply a hierarchical string. For instance, a smart meter might publish to telemetry.eus.germany.meter80492. and the routing engine utilizes wildcard matching against that hierarchy.

SPEAKER_01I want to drill into the mechanics of that matching, because if NATS is pushing 18 million messages a second, string matching across potentially millions of active subjects sounds like a massive CPU bottleneck, how does the routing table actually function? NATS uses a highly optimized data structure called a radix try for its routing table. A radix try.

SPEAKER_00Yes. When an engineer subscribes to a wildcard subject, say, using an asterisk for a single token like telemetry.us.meter 8492 or a greater than symbol for a full trailing wildcard like telemetry.us, the NAT server doesn't do linear string comparisons.

SPEAKER_01It's not just running rejects.

SPEAKER_00No, regex would be way too slow. It traverses the try in memory. The try is structured so that common prefixes are shared. This means the computational complexity of matching a published subject to thousands of wildcard subscriptions is remarkably low. It scales logarithmically, not linearly.

SPEAKER_01That explains the throughput. The sources highlight that NATS defaults to an end-to-end communication model. Many-to-many, most developers are fundamentally trained on HTTP and REST, which is strictly a one-to-one model. If you want to talk to multiple instances in HTTP, you have to inject complex infrastructure, internal DNS, reverse proxies, service meshes.

SPEAKER_00Exactly. In NATS, true end-to-end publish-subscribe is the default. A service publishes an event to a subject, and the NATS try instantly identifies all interested subscribers fanning out the payload. But where NATS truly replaces HTTP infrastructure is with its second pattern, request-reply.

SPEAKER_01Yes, this is huge. NATS allows developers to execute synchronous-style communication over an asynchronous transport. How does that actually work at the protocol level? If NATS is just a dumb pipe moving bytes, how does a request map back to the specific client that asked for it?

SPEAKER_00It's very clever. When an application makes a request, the NATS client library automatically generates a unique transient randomized reply subject, often referred to as an INBX subject.

SPEAKER_01Okay, so a temporary return address.

SPEAKER_00It embeds this reply subject in the message header before publishing. The receiving microservice processes the payload, extracts that reply subject from the header and publishes the response back to it. The NAT server instantly routes it back to the original requester. And to the developer. To the Go or Python developer writing the code, it looks exactly like a blocking HTTP call. You just await the response. But underneath, it is flowing over a highly decoupled multiplex TCP socket without requiring any dedicated connection between the two microservices.

I can see how that replaces point-to-point HTTP, but what about load balancing?

SPEAKER_01If Sourceful Energy has 50 instances of a billing microservice, we don't want all 50 processing the same request. In a REST architecture, we use an internal application load balancer. In NATs, the solution is queue groups.

SPEAKER_00Right. QGroups are built-in, distributed load balancing. When those 50 billing microservices subscribe to the orders.new subject, they also supply a QGroup string. For example, billing workers. Okay. When the NAT server's RadixTry matches a message to that subject, it detects the QGroup. Instead of fanning out the message to all 50 subscribers, the server dynamically and randomly selects exactly one subscriber from the group and delivers the payload solely to them. I want to push back on this claim that we can just delete load

balancers.

SPEAKER_01I hear this a lot in messaging circles. Sure, for internal service-to-service communication, queue groups distribute the workload. But load balancers and API gateways do a lot more than just round-robin routing. They handle SSL termination, rate limiting, and web application firewall rules. We can't just rip those out. How does NATS handle Layer 7 concerns?

SPEAKER_00That is a critical distinction, and you are entirely correct. NATS does not replace your public-facing ingress layer. You still need an API gateway or a WAF at the edge of your network to handle public internet traffic, DDoS mitigation, and SSL termination from end users' browsers.

SPEAKER_01Good, because otherwise the security team would have a heart attack.

SPEAKER_00Absolutely. What NATS eliminates is the internal east-west infrastructure. Once a request passes your edge ingress and enters your internal network, you no longer need internal DNS service discovery mechanisms like console or internal reverse proxies to route traffic between your microservices. The NAT subject acts as the service discovery and the Q group acts as the internal load balancer.

SPEAKER_01Okay, that makes sense. It radically flattens the internal mesh. And there is a brilliant historical detail in the sources regarding a circuit breaker pattern built into the early request reply implementations.

SPEAKER_00Yes. Collison designed the original request reply to inherently act as a circuit breaker. Often, you might send a request to a subject, and for fault tolerance reasons, multiple redundant backend services might actually process it and try to respond simultaneously.

SPEAKER_01You get a race condition for the response.

SPEAKER_00The original NATS client was designed to only want a single response. The millisecond, the first response flowed back through the server to the client. The client library would dynamically sever its interest in the reply subject.

SPEAKER_01It just cuts the line. Any subsequent responses from slower services were instantly dropped by the server,

SPEAKER_00saving the client application from wasting CPU cycles, evaluating redundant data.

SPEAKER_01That is incredibly elegant. Now let's scale this geographically. Because sourceful energy isn't running in a single data center, we are talking about multiple cloud regions plus physical edge hardware across the globe. This brings us to topological superpowers, clusters, superclusters, and leaf nodes. Let's start with the base unit of high availability, the cluster. Mm-hmm. A NATS cluster is designed for high availability within a single region or data center.

SPEAKER_00It relies on a full mesh topology. If you deploy five NATS servers, every server maintains a persistent direct TCP connection to the other four.

SPEAKER_01So it's fully interconnected. How do they keep the routing tables in sync? If I connect to server A and subscribe to a subject, how does server B know to send me data?

SPEAKER_00They utilize a highly efficient gossip protocol. When your client subscribes on server A, server A gossips that interest across the full mesh. Server B updates its internal interest. Try to reflect that server A has an active subscriber for that subject.

SPEAKER_01So everyone knows what everyone else wants. Crucially, because it is a full mesh, NATS enforces a strict one-hop routing maximum. A message will never bounce from server B to server C to get to server A. It goes directly. This mathematically prevents routing loops and guarantees incredibly predictable

SPEAKER_00sub-millisecond network latency within the data center.

SPEAKER_01But a full mesh topology mathematically breaks down at scale. The connection count grows exponentially. If Sourceful tries to connect 50 NAT servers across AWS US East, AWS EU Central, and Google Cloud Asia in a full mesh, the crosstalk and the expensive WAN transit costs would be a nightmare. How do we achieve global scale without bankrupting the company?

SPEAKER_00You deploy a supercluster. A supercluster connects distinct, independent regional clusters together using NATS gateways. Instead of a full global mesh, the gateways act as intelligent bridges utilizing a spline routing algorithm. The sources emphasize that these gateways are geo-aware and operate strictly in

SPEAKER_01interest-only mode. Explain how that optimizes the WAN links. In a Kafka mirror maker setup, we are usually blindly mirroring whole topics across the ocean just in case an application needs it.

SPEAKER_00That blind mirroring is exactly what NATS avoids. Let's say your US cluster is processing 500,000 smart meter readings a second on the subject grid.telemetry.us. The supercluster gateway checks the global interest graph.

SPEAKER_01And if no one in Europe cares about it. If there are zero active subscribers explicitly listening to that subject in the

SPEAKER_00European cluster, the gateway actively blocks the traffic. Not a single byte of that telemetry crosses the expensive transatlantic WAN link.

SPEAKER_01Zero egress cost.

SPEAKER_00Exactly. But the absolute millisecond in SRE in Europe spins up a dashboard and subscribes to grid.telemetry.us. The gateway detects the interest propagation and dynamically opens the flow. The data crosses the ocean only when demand exists. It is entirely autonomic.

SPEAKER_01That saves a fortune on cloud egress fees. But let's push out even further, out of the data center entirely, to the physical edge. We are talking about leaf nodes. For the Sourceful Energy Infrastructure team, this is likely the most critical architectural component.

SPEAKER_00A leaf node is arguably the ultimate enabler for secure edge computing. A leaf node is a standard, standalone NAT server binary that you deploy on constrained edge hardware. Say, the internal computer of a wind turbine or a local solar array controller. It runs locally, serving local clients, but it is configured to logically bridge back to the central supercluster.

SPEAKER_01I want to focus on the networking mechanics here, specifically for the security teams listening. Deploying edge hardware usually means begging local IT departments or cellular providers to open inbound firewall ports so the cloud can reach the device. It is a massive security vulnerability and an operational nightmare.

SPEAKER_00And that is the brilliance of the leaf node architecture. A leaf node does not wait for incoming connections. It establishes an outbound connection to the central NATs cluster, typically over standard secure ports like 443 or 7422. Because the connection originates from the inside of the local network out to the

SPEAKER_01internet, it punches right through standard corporate firewalls and carrier-grade NAT.

SPEAKER_00Yes, you don't have to touch the firewall. I see the security advantage, but I have a major concern about core capacity.

SPEAKER_01If Sourceful deploys 100,000 EV chargers, and every single one has a leaf node dialing out, we now have 100,000 persistent TLS TCP connections hitting our core cluster. Doesn't that risk massive socket exhaustion at the core?

SPEAKER_00If every message required a new connection, yes, but NATS multiplexes all traffic, hundreds or thousands of distinct subjects, requests, and streams over that single long-lived outbound TCP tunnel. Furthermore, remember the goroutine architecture we discussed earlier, a NATS core server can easily maintain millions of concurrent idle or low-traffic TCP connections in user space without kernel thread exhaustion.

SPEAKER_01Let's walk through a realistic edge case failure with a leaf node. Imagine an offshore wind turbine. It has a leaf node routing telemetry from dozens of local sensors. It's connected to the mainland via a satellite or cellular uplink. A severe storm hits and the uplink drops entirely. The turbine is physically isolated.

SPEAKER_00In a traditional architecture where sensors push directly to the cloud, all telemetry during that storm is permanently lost. But with a leaf node, you configure a local jet stream instance right on the turbine's hardware.

SPEAKER_01So you run persistence on the edge device itself.

SPEAKER_00Right. During the outage, the local sensors continue publishing. The local leaf node durably buffers all that telemetry to its local disk. Crucially, any local autonomous control systems like the blade pitch actuators continue communicating with the sensors via the local leaf node perfectly fine, completely oblivious to the internet outage.

SPEAKER_01And when the storm passes and the satellite link comes back online, The leaf node automatically reestablishes the outbound TLS tunnel to the central cluster. Because the central supercluster maintains the interest graph, it recognizes the reconnection. The central jet stream consumers automatically resume their position in the stream, and the leaf node seamlessly synchronizes all the buffered telemetry back to the

SPEAKER_00cloud, guaranteeing historical accuracy. The edge operates completely autonomously when disconnected and federates perfectly

SPEAKER_01when connected.

SPEAKER_00That is the holy grail of edge computing.

SPEAKER_01But bridging disparate networks, cloud, mobile, edge, it creates a massive security surface area. Which brings us to decentralized security and true multi-tenancy. In a high throughput system pushing millions of messages, how do you handle authentication? Traditional brokers usually rely on a centralized database or an LDAP lookup.

SPEAKER_00If you are aiming for sub-millisecond latency, requiring the broker to query an external database to validate credentials on every single connection is a catastrophic bottleneck. NATs abandon centralized authentication entirely. Instead, it relies on a fully decentralized cryptographic model using ED25599 and keys and JSON web tokens, or JWTs.

SPEAKER_01Let's break down the cryptography. Why ED25519 specifically, rather than standard RSA keys? ED2551 HINE is an elliptic curve cryptography scheme that is incredibly fast and

SPEAKER_00produces very small signatures. It is perfect for high speed verification. NATS uses these key pairs to establish a strict offline trust hierarchy consisting of three tiers, operators, accounts, and users. Walk me through that hierarchy from the perspective of Sourceful Energy's platform team. The platform team acts as the operator. This is the absolute root of trust. The operator generates an ED255.10 key pair and embeds the public key directly into the configuration of the NAT servers. The private key is kept entirely offline, perhaps in a physical vault.

SPEAKER_01Okay, so the servers only know the public key.

SPEAKER_00Right. Below the operator are accounts. An account represents a logical tenancy, the grid operations department. The operator uses its offline private key to cryptographically sign a JWT that explicitly vouches for the grid operations account.

SPEAKER_01And then the users.

SPEAKER_00Finally, below accounts are users. A user represents an actual client application like a specific telemetry microservice. The grid operations account uses its private key to sign a JWT that vouches for that specific microservice. So when that telemetry microservice actually initiates a TCP connection to the NAT

SPEAKER_01server, what happens at the packet level?

SPEAKER_00The client presents its user JWT during the initial handshake. The NATS server does not query any database. The server already holds the operator's public key and memory. It simply performs a lightning fast cryptographic validation of the signature chain. It mathematically verifies, was this user token genuinely signed by the grid operations account? And was that account genuinely signed by our root operator? If the math validates, the connection is instantly authorized.

SPEAKER_01And what about authorization? How does the server know which subjects this microservice is allowed to access? The permissions are embedded directly into the JWT payload itself as claims.

SPEAKER_00The token dictates exactly which subjects the client can publish to, which it can subscribe to, and even sets data limits. Because the token is cryptographically signed, the client cannot alter these permissions.

SPEAKER_01But what if a key is compromised? If everything is decentralized and offline, how do I revoke access without taking down the cluster?

SPEAKER_00NATS supports real-time revocation. While the authentication validation is mathematically offline, the NAT servers monitor a specialized internal system subject for security updates. If an account key is compromised, the operator publishes a revocation list to that subject. The NAT servers instantly update their in-memory security state and sever any active TCP connections utilizing that compromised keychain without requiring a server reboot.

SPEAKER_01Let's look closer at that middle tier. Accounts. The documentation describes accounts as isolated messaging containers. This appears to be the mechanism for true multi-tenancy.

SPEAKER_00It is. In standard message brokers like Kafka or RabbitMQ, you generally operate in a single global namespace. If the billing team and the logistics team both accidentally create a topic called orders.status, they start receiving each other's data, causing catastrophic logic failures. In NATS, an account is a cryptographically isolated sandbox. A subject name orders.status in account A is mathematically invisible to account B. The routing try completely segregates them.

SPEAKER_01But it's sourceful. Teams need to collaborate. If grid operations have a real-time stream of energy pricing on their subject grid.pricing.live, and the consumer mobile app team needs that data to show users their current tariff, how do they bridge the accounts?

SPEAKER_00Through explicit exports and imports. Grid operations configures their account to export the grid.pricing.live subject. The consumer team configures their account to import it, but here is the architectural masterstroke. The importing team can dynamically remap the subject namespace locally.

SPEAKER_01What do you mean by remapping?

SPEAKER_00When the consumer team imports the stream, they don't have to adopt grid operations naming convention. They can configure the import to map incoming data to internal.app.tariffs. The NAT server seamlessly handles this transition in memory. The consumer team's microservices subscribe to internal.app.tariffs, completely unaware of the original subject name. It prevents namespace collisions and completely decouples team architectures.

SPEAKER_01That is incredibly powerful for large organizations. But I have to play the role of the enterprise security auditor here. Sourceful Energy already has a massive investment in Okta or Active Directory for identity management. We can't just tell the chief information security officer that we are ignoring the corporate LDAP directory in favor of local cryptographic keys.

SPEAKER_00You don't have to. NATS recently introduced an elegant bridge for this exact scenario called auth calouts. While the decentralized JWT model is the most performant, Auth-calouts allow NATs to delegate authentication for specific connections to an external service. When a client connects perhaps using a standard Oath-bearer token, the NAT server pauses the handshake. It makes a high-speed internal request to a dedicated Authenticator microservice. That microservice validates the token against Okta or LDA. If approved,

the Authenticator service dynamically generates a decentralized NATs JWT on the fly

SPEAKER_00signs it, and hands it back to the NAT server. So the data plane continues to operate on high-speed decentralized cryptography,

SPEAKER_01but the control plane identity is still anchored in the legacy enterprise directory.

SPEAKER_00Exactly. It is the perfect bridge, allowing you to deploy NAB seamlessly within strict enterprise environments while retaining the performance benefits of local cryptographic validation.

SPEAKER_01We are reaching the final phase of this architecture review. As senior engineers, the Sourceful team is constantly evaluating the competitive landscape. If you advocate for NATs, you will immediately be asked, why not use Kafka? Why not RabbitMQ? What about MQTT for the edge? We need to do a hard architectural teardown. Let's start with the heavyweight, NATs versus Apache Kafka.

SPEAKER_00This is the most frequent comparison, and architecturally it is often a comparison of fundamentally different paradigms. Apache Kafka was engineered at LinkedIn to be a distributed, durable, append-only log. It was designed to ingest massive volumes of data and hold it durably on disk so that heavy analytics engines like Hadoop or Spark could process it asynchronously.

SPEAKER_01Right. It relies heavily on sequential disk I.O. and the Linux OS page cache.

SPEAKER_00Yes. And to scale that disk I.O., Kafka relies on partitions. When you create a topic, you split it into, say, 20 partitions. This allows 20 different disk arrays to write simultaneously. But that partition architecture dictates your consumption scaling. You utilize consumer groups. If you have 20 partitions, your consumer group can have a maximum of 20 active consumers. If you spin up a 21st consumer microservice, it sits completely idle.

SPEAKER_01And if a consumer crashes, Kafka has to perform a consumer group rebalance, which literally stops the world for that topic while it reassigns partitions. It causes massive latency spites.

SPEAKER_00Precisely. Kafka sacrifices real-time latency and dynamic routing for strict ordering and massive historical retention. NATS, conversely, routes purely on subjects in memory. Queue groups in NATS are not bound by partitions. If you have a NATS queue group with 20 workers and you experience a traffic spike, you can instantly spin up 50 more workers, and NATS immediately begins load balancing across all 70. NATS Jetstream overlaps with Kafka's durable streaming, but because NATS separates the routing from the storage core

versus Jetstream, it provides dynamic scalability that Kafka's partition-bound architecture simply

SPEAKER_00cannot match for microservice communication.

SPEAKER_01Okay, what about RabbitMQ? It has been the enterprise standard for complex routing for a decade.

SPEAKER_00RabbitMQ implements the AMQP protocol. Its primary strength is the Exchange, a highly complex writing engine that allows you to define intricate rules for how messages flow between queues. The tradeoff is operational complexity and fragility at scale. RabbitMQ is built on Erlang, and it utilizes a database called Amnesia to track cluster state.

SPEAKER_01Amnesia is notorious for handling network partitions poorly.

SPEAKER_00extremely poorly. If a RabbitMQ cluster experiences a network split, the nodes can easily form separate clusters, a true split brain. When the network heals, amnesia does not automatically merge them. It usually requires manual intervention and often results in dropped messages. NATS trades the hyper complexity of AMQP exchanges for the elegant simplicity of subject wildcards. The NATS Radix try is vastly faster than RapidMQ exchanges, and because NATS utilizes a gossip protocol for the base cluster and strict RAF consensus for Jetstream,

SPEAKER_00it recovers from network partitions autonomously and safely.

SPEAKER_01Finally, let's look at the absolute edge. SourceFull deploys microcontrollers on solar panels that have practically zero RAM and unstable cellular connections. For that, MQTT is the gold standard. It is built-in QoS levels and retained messages. Does NATS attempt to replace MQTT?

SPEAKER_00It doesn't have to. In industrial IoT, the modern architectural pattern is the unified namespace, or UNS. The goal is to create a single, federated hierarchy of all operational data. NATS is the perfect backbone for a UNS, but MQTT is still the right protocol for the extreme edge devices.

SPEAKER_01So how do you bridge them? Usually that requires a clunky translation gateway middleware that just adds latency and points of failure.

SPEAKER_00The NATS engineering team solved this natively. The NATS server binary actually includes an embedded MQTT broker. You can configure NATS to listen on port 1883. Your legacy MQTT sensors connect to the NATS server, completely oblivious that it isn't a standard MQTT broker. They publish their payloads. NATS instantly ingests the MQTT packets, translates them into internal NATS messages, and maps the MQTT topics directly to NATS subjects.

SPEAKER_01So a temperature sensor publishes via lightweight MQTT, and a high-speed Go microservice in the cloud can instantly consume that data via a NATS jet stream without any external translation layers.

SPEAKER_00Exactly. You retain the vast hardware ecosystem compatibility of MQTT at the physical edge, but you immediately ingest that data into the 18 million message-a-second nervous system of NATS for your back-end analytics and microservices. It bridges the gap seamlessly.

SPEAKER_01That is a phenomenal architectural synergy. We have covered an immense amount of ground today. To the Sourceful Energy Engineering team, our mission was to deconstruct NATs and show you how to utilize it to its maximum potential. What we've explored is that adopting NATs is not merely swapping out a message queue. It is fundamentally rethinking network topology. It means adopting subject-based routing to eradicate layers of reverse proxies and internal load balancers. It means utilizing core NATs for blistering real-time telemetry

and jet stream for

SPEAKER_01resilient raft-backed ledgers. It means securing your physical edge assets with outbound dialing leaf nodes that survive cellular outages. And it means executing all of this with a single, highly optimized 15 megabyte Go binary.

SPEAKER_00The ultimate goal is operational simplicity. By shifting the complexity of routing, load balancing, and state replication down into the autonomic infrastructure layer, your engineering teams are free to focus entirely on the business logic of optimizing the energy grid.

SPEAKER_01Before we conclude this session, we want to leave you with a final architectural concept to consider as you design the next iteration of your platform.

SPEAKER_00Think about the foundation of how we build distributed systems. For decades, we have relied almost entirely on synchronous point-to-point HTTP and REST APIs. That architecture forces every layer of our software to constantly wait, block threads, manage complex timeouts, and explicitly know the IP address or DNS name of its dependencies. But as we move into an era defined by real-time AI inferences, autonomous edge computing, and highly fluid containerized environments, what if the very concept of an IP address becomes completely

irrelevant to

SPEAKER_00application developers? What if the future of all software architecture is simply expressing an interest in a semantic subject, entrusting a global autonomic nervous system to instantly route the answers to you dynamically wherever you happen to be connected in the world? That is a profound paradigm shift, and it is the reality that NATS enables today.

SPEAKER_01Thank you for joining us on this deep dive into the architecture of NATS. To the engineers at Sourceful Energy, we hope this analysis equips you to build faster, leaner, and exponentially more resilient systems. Until next time.

Open the transcript file

Hosts and Guests

Nobody is credited on this episode yet.

Credit the people on this episode

Be the first to rate this episode

More episodes

All episodes
  1. Counting Years

    Nov 22, 202642 minAudio

    Coordinated with Fredrik, Episode 127. Forty-two minutes on how a company gets its price: what a multiple counts, why the same krona can be worth seven years in one company and twenty-seven in another, how a rise in...

    Credit the people on this episode

  2. Shoulder Check

    Oct 31, 202650 minAudio

    Fifty minutes on two runs a day apart: the rest of Vancouver, and the road from ten Helium gateways to physics first. An interview with Lily. On Thursday I answered her questions in English; on Friday I went back to...

    Credit the people on this episode

  3. We Live Where We Are

    Oct 27, 202637 minAudio

    Thirty-seven minutes on two runs a day apart: the two years after the money came in, and home. An interview with Lily. I answered her questions in Swedish while running; the English voice you hear is my cloned voice...

    Credit the people on this episode

  4. Momentum

    Oct 24, 202639 minAudio

    Thirty-nine minutes on the two years before a term sheet arrived on my birthday, and what it took to turn it into money. An interview with Lily. I answered her questions in Swedish on a fifteen-kilometre run; the...

    Credit the people on this episode

  5. EP123: The Drive. Somebody Has to Say Yes

    Oct 15, 202634 minAudio

    This episode started in a car. A clear October day, low sun, the drive from Kalmar to Stockholm. I could have flown, and it would have been faster. But the hours in the car are a different kind of time. The car keeps...

    Credit the people on this episode