🏗️ Architecture

NATS

Neural Autonomic Transport System

A lightweight, high-performance messaging system designed for cloud-native environments. A CNCF (Cloud Native Computing Foundation) incubating project, it integrates seamlessly with the Kubernetes ecosystem. A single Go binary (under 10MB) handles millions of messages per second, with native support for Pub/Sub, Request/Reply, and Queue Groups patterns.

📖 Detailed Explanation

NATS is an open-source messaging system first developed by Derek Collison in 2010 in Ruby and later rewritten in Go. Under the philosophy of "Always on and available," it was designed with simplicity and performance as top priorities. It is currently a CNCF incubating project and is becoming established as the standard for service-to-service communication in Kubernetes environments.

NATS's core philosophy is "Simplicity is a Feature." Running a single binary starts a messaging server immediately, without complex configuration. Core NATS, which uses at-most-once delivery by default, provides ultra-low latency (sub-millisecond), and enabling JetStream adds support for At-least-once/Exactly-once delivery and message persistence.

Internally, NATS uses a text-based protocol, which makes debugging easy, and Subject-based addressing enables flexible message routing. Through clustering, super-clusters (multi-region), and Leaf Nodes, you can build a global-scale messaging infrastructure.

In practice, NATS is widely used for IoT device communication, microservice event buses, real-time notification systems, and distributed system coordination. It is much lighter than Kafka while still meeting most messaging requirements, and it is called "the connective tissue for cloud native applications."

NATS Core Messaging Patterns

Pub/Sub (Publish/Subscribe)

When a message is published to a Subject, all clients subscribed to that Subject receive it. 1:N broadcast.

Queue Groups

The message is delivered to only one of the subscribers belonging to the same queue group. A load-balanced worker pattern.

Request/Reply

Synchronous request-response pattern. The client sends a request and the server responds. Timeout built in.

JetStream

Persistence layer. Message storage, replay, and Consumer management. Composed of Streams and Consumers.

💻 Code Example

Go - NATS Basic Pub/Sub

package main

import (
    "fmt"
    "github.com/nats-io/nats.go"
    "time"
)

func main() {
    // NATS 서버 연결
    nc, err := nats.Connect(nats.DefaultURL) // nats://localhost:4222
    if err != nil {
        panic(err)
    }
    defer nc.Close()

    // 구독자 설정 (비동기)
    sub, _ := nc.Subscribe("orders.created", func(msg *nats.Msg) {
        fmt.Printf("📬 Received: %s\n", string(msg.Data))
    })
    defer sub.Unsubscribe()

    // 메시지 발행
    nc.Publish("orders.created", []byte(`{"orderId": "12345", "amount": 99000}`))

    // 동기 구독 (Request/Reply 패턴)
    nc.Subscribe("api.users.get", func(msg *nats.Msg) {
        nc.Publish(msg.Reply, []byte(`{"userId": "1", "name": "Kim"}`))
    })

    // Request/Reply 요청
    response, _ := nc.Request("api.users.get", []byte(`{"id": "1"}`), 2*time.Second)
    fmt.Printf("📨 Response: %s\n", string(response.Data))

    time.Sleep(100 * time.Millisecond)
}

Go - JetStream (Persistent Messaging)

package main

import (
    "context"
    "fmt"
    "github.com/nats-io/nats.go"
    "github.com/nats-io/nats.go/jetstream"
)

func main() {
    nc, _ := nats.Connect(nats.DefaultURL)
    defer nc.Close()

    js, _ := jetstream.New(nc)
    ctx := context.Background()

    // Stream 생성 (메시지 저장소)
    stream, _ := js.CreateOrUpdateStream(ctx, jetstream.StreamConfig{
        Name:      "ORDERS",
        Subjects:  []string{"orders.>"},  // orders.* 패턴 매칭
        Storage:   jetstream.FileStorage, // 파일 기반 영속성
        Retention: jetstream.LimitsPolicy,
        MaxMsgs:   10000,
        MaxAge:    24 * time.Hour,
    })
    fmt.Printf("✅ Stream created: %s\n", stream.CachedInfo().Config.Name)

    // 메시지 발행 (영속적)
    js.Publish(ctx, "orders.created", []byte(`{"orderId": "ORD-001"}`))
    js.Publish(ctx, "orders.paid", []byte(`{"orderId": "ORD-001"}`))

    // Consumer 생성 (메시지 소비자)
    consumer, _ := stream.CreateOrUpdateConsumer(ctx, jetstream.ConsumerConfig{
        Durable:       "order-processor",
        FilterSubject: "orders.created",
        AckPolicy:     jetstream.AckExplicitPolicy,
    })

    // 메시지 Fetch (Pull 기반)
    batch, _ := consumer.Fetch(10, jetstream.FetchMaxWait(5*time.Second))
    for msg := range batch.Messages() {
        fmt.Printf("📦 Processing: %s\n", string(msg.Data()))
        msg.Ack() // 명시적 ACK
    }
}

Python - NATS Async Client

import asyncio
import nats
from nats.errors import TimeoutError

async def main():
    # NATS 서버 연결
    nc = await nats.connect("nats://localhost:4222")

    # 구독 핸들러
    async def message_handler(msg):
        subject = msg.subject
        data = msg.data.decode()
        print(f"📬 [{subject}] {data}")

        # Request/Reply인 경우 응답
        if msg.reply:
            await nc.publish(msg.reply, b'{"status": "processed"}')

    # 와일드카드 구독
    # '*' = 단일 토큰, '>' = 다중 토큰
    await nc.subscribe("events.>", cb=message_handler)

    # Queue Group 구독 (로드 밸런싱)
    await nc.subscribe(
        "tasks.process",
        queue="workers",  # 같은 그룹 내 하나의 워커만 수신
        cb=message_handler
    )

    # 메시지 발행
    await nc.publish("events.user.signup", b'{"userId": "123"}')
    await nc.publish("events.order.created", b'{"orderId": "456"}')

    # Request/Reply (타임아웃 2초)
    try:
        response = await nc.request(
            "api.health",
            b'ping',
            timeout=2.0
        )
        print(f"📨 Health: {response.data.decode()}")
    except TimeoutError:
        print("❌ Request timed out")

    await asyncio.sleep(1)
    await nc.drain()

asyncio.run(main())

Docker Compose - NATS Cluster

# docker-compose.yml
version: '3.8'
services:
  nats-1:
    image: nats:2.10-alpine
    container_name: nats-1
    ports:
      - "4222:4222"   # 클라이언트 포트
      - "8222:8222"   # 모니터링 포트
    command: >
      -js                           # JetStream 활성화
      -sd /data                     # 데이터 디렉토리
      --cluster_name NATS_CLUSTER
      --cluster nats://0.0.0.0:6222
      --routes nats://nats-2:6222,nats://nats-3:6222
    volumes:
      - nats-1-data:/data

  nats-2:
    image: nats:2.10-alpine
    container_name: nats-2
    command: >
      -js -sd /data
      --cluster_name NATS_CLUSTER
      --cluster nats://0.0.0.0:6222
      --routes nats://nats-1:6222,nats://nats-3:6222
    volumes:
      - nats-2-data:/data

  nats-3:
    image: nats:2.10-alpine
    container_name: nats-3
    command: >
      -js -sd /data
      --cluster_name NATS_CLUSTER
      --cluster nats://0.0.0.0:6222
      --routes nats://nats-1:6222,nats://nats-2:6222
    volumes:
      - nats-3-data:/data

volumes:
  nats-1-data:
  nats-2-data:
  nats-3-data:

📊 Performance & Comparison

NATS vs Other Messaging Systems

Characteristics NATS Core NATS JetStream Kafka RabbitMQ
Delivery Guarantee At-most-once At-least/Exactly-once At-least-once At-least-once
Latency <100μs ~1ms ~5-10ms ~1-5ms
Binary Size ~10MB ~10MB ~100MB+ ~50MB
Memory Usage ~20MB ~100MB+ 1GB+ ~200MB+
Dependency None None ZooKeeper/KRaft Erlang
Clustering Built-in Built-in (Raft) Built-in (Raft) Built-in
Throughput per Second 10M+ msg/s 1M+ msg/s 1M+ msg/s ~100K msg/s

JetStream Performance (Single Server, 2024 Benchmark)

Scenario Throughput Latency (p99) Message Size
Memory Storage 500K msg/s 0.5ms 256B
File Storage (SSD) 200K msg/s 2ms 256B
3-Node Cluster 150K msg/s 5ms 256B

✅ NATS selection criteria: When you need IoT, real-time communication, a microservice event bus, or lightweight messaging. Kafka is suited to high-volume log streaming and event sourcing.

🗣️ Examples of Practical Conversations

💬 In an Architecture Review Meeting

"If we adopt NATS for event communication between microservices, operational complexity drops significantly compared to Kafka. It clusters as a single binary without ZooKeeper, and its memory footprint is about 1/50. Events that need persistence can be handled with JetStream."

💬 In a technical interview

"The difference between NATS Core and JetStream? Core is fire-and-forget with at-most-once delivery, while JetStream stores messages in a Stream so that Consumers can replay them. It replicates data via Raft consensus and guarantees at-least-once based on ACKs."

💬 In an IoT Project

"We're collecting real-time telemetry from 100,000 devices with NATS. We connected the edge and the cloud with Leaf Nodes and scaled out the processing workers horizontally with Queue Groups. Latency per message is under 1ms, so it's perfect for real-time monitoring."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌ Message loss in Core NATS: Consumers that are absent or slow miss messages. If you need persistence, be sure to use JetStream.

❌ Subject naming mistakes: "orders.created" and "orders.Created" are different Subjects. Use lowercase and the dot (.) delimiter consistently.

❌ Unacknowledged JetStream Consumer messages: Under the AckExplicit policy, if you do not ACK, the message is redelivered. Be sure to call msg.Ack() after processing.

✅ The right way: In development, test Subject subscribe/publish with nats-cli, and in production, monitor with Prometheus metrics and Grafana dashboards.

🔗 Related Terms

📚 Learn More