DEV Community

Alex Spinov
Alex Spinov

Posted on

NATS Has a Free API: The Messaging System Built for Cloud-Native

RabbitMQ needs Erlang. Kafka needs Java and ZooKeeper. NATS needs... nothing. A single 15MB binary handles pub/sub, request-reply, streaming, and key-value.

What Is NATS?

NATS is a connective technology for distributed systems. Pub/sub messaging, request-reply, streams, key-value store, object store — all in a single, lightweight server.

# Install and run
docker run -p 4222:4222 nats:latest
Enter fullscreen mode Exit fullscreen mode

Pub/Sub

import nats

async def main():
    nc = await nats.connect("nats://localhost:4222")

    # Subscribe
    async def handler(msg):
        print(f"Received: {msg.data.decode()}")

    sub = await nc.subscribe("events.>", cb=handler)

    # Publish
    await nc.publish("events.user.signup", b'{"user": "alice"}')
    await nc.publish("events.order.created", b'{"order": 123}')
Enter fullscreen mode Exit fullscreen mode

JetStream (Persistent Streaming)

# Create a stream
js = nc.jetstream()
await js.add_stream(name="ORDERS", subjects=["orders.>"])

# Publish with acknowledgment
ack = await js.publish("orders.new", b'{"item": "laptop", "qty": 1}')
print(f"Sequence: {ack.seq}")

# Durable consumer (survives restarts)
sub = await js.subscribe("orders.new", durable="order-processor")
async for msg in sub.messages:
    print(f"Processing order: {msg.data.decode()}")
    await msg.ack()
Enter fullscreen mode Exit fullscreen mode

Key-Value Store

kv = await js.create_key_value(bucket="config")
await kv.put("feature.dark-mode", b"enabled")
entry = await kv.get("feature.dark-mode")
print(entry.value)  # b"enabled"

# Watch for changes
watcher = await kv.watch("feature.>")
async for entry in watcher:
    print(f"{entry.key} changed to {entry.value}")
Enter fullscreen mode Exit fullscreen mode

Why NATS

Feature NATS Kafka RabbitMQ
Binary size 15MB 500MB+ 100MB+
Dependencies None JVM, ZooKeeper Erlang
Latency <1ms 5-10ms 2-5ms
Connections 1M+ 10K 10K
Built-in KV Yes No No
  • 15MB binary — deploy anywhere, even edge devices
  • <1ms latency — faster than any alternative
  • 1M+ connections — per server
  • Multi-pattern — pub/sub + request/reply + streaming + KV in one system
  • LeafNodes — extend NATS to edge locations transparently

Building distributed systems? Check out my developer tools or email spinov001@gmail.com.

Top comments (0)