NATS | 언제, 왜, 어떻게
HTTP 대신 NATS를 언제, 왜 쓰는지. pub/sub, request-reply, 큐 그룹, JetStream을 TypeScript 예제로.
8분 분량nats · microservices
NATS는 빠르고 단순하며 회복력 있는 서비스를 만들기 위한 고성능 메시징 시스템입니다. 이 가이드는 NATS를 언제, 왜 써야 하는지, HTTP와 어떻게 다른지 설명하고, Pub/Sub, Request-Reply, 작업 큐, JetStream 영속성을 간결한 TypeScript/JavaScript 예제로 보여 줍니다.
NATS를 써야 할 때
- HTTP가 오버헤드가 되는 마이크로서비스 간 저지연 메시징.
- 팬아웃(발행자 하나 → 구독자 여럿) 또는 이벤트 기반 아키텍처.
- 경쟁 소비자로 작업을 병렬 처리하는 작업 큐.
- HTTP 없는 Request-Reply RPC (NATS를 통한 서비스 간 호출).
- JetStream을 이용한 영속 스트림, 재생, at-least-once 전달.
- 다언어·멀티플랫폼 시스템 (다양한 스택용 NATS 클라이언트가 있습니다).
HTTP를 유지해야 할 때:
- 브라우저와 파트너용 공개 API처럼 캐시와 프록시가 중요한 경우.
- 엄격한 REST 의미론, 표준 중개자, API 게이트웨이가 필수인 경우.
왜 NATS인가
- 단순함: 토픽/큐/익스체인지 대신 subject.
- 속도: 가벼운 프로토콜, 낮은 지연, 높은 처리량.
- 패턴: Pub/Sub, Request-Reply, 큐 그룹, Key/Value, Object Store.
- 확장성: 클러스터링과 leaf node, JetStream을 이용한 글로벌 메시.
- 신뢰성(JetStream): 영속성, 재생, ack 기반 소비자.
HTTP와 비교한 통신 패턴
- Pub/Sub(fire-and-forget 이벤트) ≈ HTTP 웹훅 브로드캐스트. 다만 여러 구독자에게 푸시하며, 백프레셔는 소비자 설계에 달려 있습니다.
- Request-Reply(RPC) ≈ HTTP 요청/응답. 다만 하나의 TCP 연결 위에서 동작해 지연이 낮고 부하 분산이 내장되어 있습니다.
- 큐 그룹 ≈ 부하 분산된 HTTP 워커. 그룹 안에서 소비자 하나만 각 메시지를 받습니다.
- 스트림(JetStream) ≈ 영속 이벤트 로그를 위한 HTTP + 큐 + 데이터베이스. pull/push 소비자와 재생을 지원합니다.
Request-Reply, 헤더, subject 규칙으로 NATS 위에 HTTP 같은 의미론을 만들 수 있고, 필요 없는 곳에서는 HTTP 서버를 둘 필요가 없습니다.
준비
- 로컬에서 NATS 실행 (Docker):
docker run -p 4222:4222 -ti nats:2 -js- 클라이언트 설치:
npm i nats- 연결 (TS/JS):
import { connect, StringCodec } from "nats";
async function main() {
const nc = await connect({ servers: "nats://localhost:4222" });
const sc = StringCodec();
console.log("connected:", nc.getServer());
// Close gracefully
const done = nc.closed();
nc.closed().then(() => console.log("connection closed"));
process.on("SIGINT", async () => {
await nc.drain();
});
}
main();Pub/Sub (브로드캐스트)
발행자:
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
nc.publish(
"orders.created",
sc.encode(JSON.stringify({ id: "o1", total: 42 }))
);
await nc.flush();
await nc.drain();
})();구독자:
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
const sub = nc.subscribe("orders.created");
for await (const m of sub) {
console.log("event", m.subject, JSON.parse(sc.decode(m.data)));
}
})();subject 설계 팁: 점으로 구분한 명사/동사를 쓰세요 (orders.created, payments.captured).
Request-Reply (HTTP 같은 RPC)
서비스 (응답자):
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
const sub = nc.subscribe("inventory.get");
for await (const m of sub) {
const { sku } = JSON.parse(sc.decode(m.data));
const qty = 7; // lookup...
m.respond(sc.encode(JSON.stringify({ sku, qty })));
}
})();클라이언트 (요청자):
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
const msg = await nc.request(
"inventory.get",
sc.encode(JSON.stringify({ sku: "SKU-123" })),
{ timeout: 1000 }
);
console.log("reply:", JSON.parse(sc.decode(msg.data)));
})();참고: 헤더(import { headers })를 붙여 인증, 상관관계 ID, content type 같은 메타데이터를 전달할 수 있습니다.
작업 큐 (경쟁 소비자)
큐 그룹 안에서 소비자 하나만 각 메시지를 받습니다.
구독 워커:
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
// queue: "workers"
const sub = nc.subscribe("images.resize", { queue: "workers" });
for await (const m of sub) {
const job = JSON.parse(sc.decode(m.data));
console.log("processing", job.id);
}
})();발행자:
import { connect, StringCodec } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
for (let i = 1; i <= 10; i++)
nc.publish("images.resize", sc.encode(JSON.stringify({ id: i })));
await nc.drain();
})();JetStream (영속 스트림, 재생)
스트림을 만들고, 발행하고, 영속 소비자로 소비합니다.
import { connect, StringCodec, consumerOpts } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
const jsm = await nc.jetstreamManager();
// idempotent upsert of a stream
await jsm.streams
.add({ name: "ORDERS", subjects: ["orders.*"] })
.catch(() => {});
const js = nc.jetstream();
await js.publish("orders.created", sc.encode(JSON.stringify({ id: "o1" })));
const opts = consumerOpts();
opts.durable("ORDERS_WORKER");
opts.manualAck();
opts.ackExplicit();
opts.deliverAll(); // or .startSequence / .startTime
const sub = await js.subscribe("orders.*", opts);
for await (const m of sub) {
const ev = JSON.parse(sc.decode(m.data));
console.log("replayed/event:", ev);
m.ack(); // at‑least‑once
}
})();이 밖에도 Key/Value 저장소(await nc.jetstream().views.kv(...))와 blob용 Object Store가 있습니다.
NATS 위에 HTTP 같은 API 설계하기
- subject를 "라우트"처럼:
svc.user.get,svc.user.update. - 동기 작업은 Request-Reply, 도메인 이벤트는 Pub/Sub.
authorization,x-correlation-id,content-type은 헤더로.- 서비스 디스커버리: 응답자를 여러 개 등록하면 NATS가 요청을 분산합니다.
- 버전 관리: subject에 접두사를 붙입니다 (예:
v1.svc.user.get).
헤더 예제:
import { connect, StringCodec, headers } from "nats";
const sc = StringCodec();
(async () => {
const nc = await connect({ servers: "nats://localhost:4222" });
const h = headers();
h.set("authorization", "Bearer <token>");
h.set("content-type", "application/json");
const msg = await nc.request(
"v1.svc.user.get",
sc.encode(JSON.stringify({ id: "u1" })),
{ headers: h, timeout: 1000 }
);
console.log(JSON.parse(sc.decode(msg.data)));
})();운영 팁
request()에 타임아웃을 걸어 호출이 멈춰 있지 않게 하세요.- 종료 전에 drain해서 깔끔하게 내리세요 (
await nc.drain()). - subject 이름과 헤더를 표준화하세요 (계약).
- 영속성과 백프레셔가 필요하면 수동 ack를 쓰는 JetStream 소비자를 쓰세요.
- 중복 없이 수평 확장하려면 큐 그룹을 쓰세요.
장점 (TL;DR)
- 서비스 간 통신에서 HTTP보다 낮은 지연과 적은 리소스.
- 추가 인프라 없이 내장된 패턴 (큐, RPC, 스트림).
- 큐 그룹과 클러스터링을 통한 수평 확장.
- JetStream을 통한 영속성, 재생, at-least-once 전달.
- 다언어 클라이언트, 단순한 운영 모델.