gRPC | 언제, 왜, 어떻게

서비스 간 트래픽에서 gRPC가 REST보다 나은 경우. 단항·스트리밍 RPC, 데드라인, 오류, 보안을 Node.js 예제로.

gRPC는 HTTP/2와 Protocol Buffers 위에 만들어진 고성능 RPC 프레임워크입니다. 이 가이드는 gRPC를 언제 쓰는지, 서비스 간 트래픽에서 왜 HTTP/REST 대신 선택하는지 다루고, 단항 RPC, 스트리밍, 데드라인, 오류, 보안, 모범 사례를 간결한 Node.js(JavaScript) 예제로 보여 줍니다.

계약 하나, 양쪽에서 생성ABC123hello.protosource of truthclient stubgenerated02HTTP/2 · TLSdeadlineGreeter servergenerated044 RPC kindsunary · server stream · client stream · bidiONE CHANNELcodegencodegenmultiplexed
그림 1계약 하나, 양쪽에서 생성

gRPC를 써야 할 때

  • 백엔드 내부의 저지연 서비스 간 호출.
  • 강하게 타입이 지정되고 진화 가능한 계약 (Proto3, 하위 호환성).
  • HTTP/2 위의 효율적인 스트리밍 (서버/클라이언트/양방향).
  • 연결 멀티플렉싱과 부하 상황에서 더 나은 꼬리 지연.
  • 생성된 스텁을 통한 다언어 상호 운용성.

HTTP/REST가 나은 경우:

  • 공개 API, 브라우저나 파트너 대상 API (캐시/프록시/CDN).
  • REST 의미론과 더 넓은 HTTP 생태계 (게이트웨이, 캐시, 도구).

왜 gRPC인가

  • 효율: HTTP/2, 헤더 압축, 멀티플렉싱, 진짜 스트리밍.
  • 계약: .proto가 단일 진실 공급원, 클라이언트와 서버 코드 생성.
  • 안전한 진화: optional 필드, 안정적인 필드 번호, 바이너리 호환성.
  • 관측과 제어: 데드라인, 취소, 표준화된 상태 코드.
  • 생태계: 인터셉터, 부하 분산, mTLS, 리졸버, 헬스 체크.

HTTP/REST와 비교한 패턴

  • 단항 RPC ≈ REST 요청/응답. 다만 오버헤드가 적고 타입이 강합니다.
  • 서버 스트리밍 ≈ 롱 폴링/SSE. 다만 바이너리이고 효율적입니다.
  • 클라이언트 스트리밍 ≈ 애플리케이션 수준 재시도 없이 배치/청크 업로드.
  • 양방향 스트리밍 ≈ WebSocket. 백프레셔와 .proto 계약이 있습니다.

외부에는 REST를, 내부에는 gRPC를 쓰거나, 앞단에 HTTP/JSON → gRPC 게이트웨이를 둘 수 있습니다.


빠른 시작 (Node.js)

  1. 의존성 설치:
spec · bash
npm i @grpc/grpc-js @grpc/proto-loader
  1. 계약 정의 (protos/hello.proto):
spec · proto
syntax = "proto3";
package hello;

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  rpc StreamGreetings (HelloRequest) returns (stream HelloReply) {}
}

message HelloRequest { string name = 1; }
message HelloReply { string message = 1; }
  1. 서버 (단항 + 서버 스트리밍):
spec · js
const path = require("node:path");
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const packageDefinition = protoLoader.loadSync(
  path.join(__dirname, "protos/hello.proto"),
  {
    keepCase: false,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true,
  }
);
const proto = grpc.loadPackageDefinition(packageDefinition).hello;

function sayHello(call, callback) {
  const name = call.request && call.request.name ? call.request.name : "world";
  callback(null, { message: `Hello, ${name}` });
}

async function streamGreetings(call) {
  const name = call.request && call.request.name ? call.request.name : "world";
  for (const i of [1, 2, 3]) {
    call.write({ message: `Hello ${name} #${i}` });
    await new Promise((r) => setTimeout(r, 300));
  }
  call.end();
}

const server = new grpc.Server();
server.addService(proto.Greeter.service, {
  SayHello: sayHello,
  StreamGreetings: streamGreetings,
});
server.bindAsync("0.0.0.0:50051", grpc.ServerCredentials.createInsecure(), () =>
  server.start()
);
console.log("gRPC server on 50051");
  1. 클라이언트 (단항 + 서버 스트리밍 + 데드라인):
spec · js
const path = require("node:path");
const grpc = require("@grpc/grpc-js");
const protoLoader = require("@grpc/proto-loader");

const packageDefinition = protoLoader.loadSync(
  path.join(__dirname, "protos/hello.proto")
);
const proto = grpc.loadPackageDefinition(packageDefinition).hello;
const client = new proto.Greeter(
  "localhost:50051",
  grpc.credentials.createInsecure()
);

// Unary with deadline
const deadline = new Date(Date.now() + 500); // 500ms
client.SayHello({ name: "Ada" }, { deadline }, (err, res) => {
  if (err) return console.error("error:", err.code, err.message);
  console.log("unary:", res.message);
});

// Server streaming
const stream = client.StreamGreetings({ name: "Ada" });
stream.on("data", (m) => console.log("stream:", m.message));
stream.on("end", () => console.log("done"));

RPC 종류

  • 단항: 요청 1 → 응답 1. 데드라인을 쓰고 ServiceError.code로 오류를 처리합니다.
  • 서버 스트리밍: 1→N 응답. data를 듣고 end로 마무리합니다.
  • 클라이언트 스트리밍: N→1 응답. 배치에 유용하며 end로 끝냅니다.
  • 양방향: N↔N. 메시지 프로토콜을 단순하게 유지하고 순서를 문서화하세요.

팁: 거대한 메시지는 피하세요. 잘게 나누거나 외부 객체 저장소에 대한 참조를 넘기는 편이 낫습니다.


Protocol Buffers (안전한 진화)

  • 필드 번호를 재사용하지 말고, 더 이상 쓰지 않는 필드는 reserved로 표시하세요.
  • 필드를 지워 호환성을 깨기보다 optional을 쓰세요.
  • 비즈니스 오류는 gRPC 상태와 필요할 때 구조화된 세부 정보로 표현하세요.

진화 예제:

spec · proto
message User {
  string id = 1;
  string email = 2; // reserved 3 (old phone)
  optional string display_name = 4;
}

reserved 3; // legacy field

오류, 데드라인, 재시도

  • 항상 데드라인을 쓰세요. 무한정 기다리는 대기열을 만들지 마세요.
  • 취소를 전파하세요. 클라이언트가 취소하면 서버 작업도 멈춰야 합니다.
  • 멱등한 코드(UNAVAILABLE, DEADLINE_EXCEEDED)만 지수 백오프와 지터로 재시도하세요.
  • 도메인 오류를 알맞은 코드(FAILED_PRECONDITION, PERMISSION_DENIED, NOT_FOUND)에 매핑하세요.

코드 조각 (Node.js):

spec · js
const grpc = require("@grpc/grpc-js");

function withDeadline(ms) {
  return { deadline: new Date(Date.now() + ms) };
}

function shouldRetry(code) {
  return (
    code === grpc.status.UNAVAILABLE || code === grpc.status.DEADLINE_EXCEEDED
  );
}

보안

  • 기본은 TLS, 내부 메시에는 mTLS를 고려하세요.
  • SAN/호스트 이름을 검증하고 인증서를 교체하세요.
  • 애플리케이션 수준 인증: 메타데이터에 JWT/OIDC (authorization: Bearer ...).

TLS 예제 (클라이언트):

spec · js
const grpc = require("@grpc/grpc-js");
const { readFileSync } = require("node:fs");

const rootCerts = readFileSync("certs/ca.pem");
const creds = grpc.credentials.createSsl(rootCerts);
// const client = new proto.Greeter("greeter.prod:443", creds);

관측성

  • 인터셉터(클라이언트/서버)로 호출을 기록하세요.
  • 메트릭: 메서드별 지연, 상태 코드, 동시성.
  • 분산 추적: 메타데이터로 컨텍스트를 전파하고 추출하세요.

클라이언트 인터셉터 (최소한의 로깅):

spec · js
const grpc = require("@grpc/grpc-js");

const loggingInterceptor = (options, nextCall) => {
  const method = options.method_definition.path;
  const start = Date.now();
  const requester = {
    start: (metadata, listener, next) => {
      const newListener = {
        onReceiveStatus: (status, nextStatus) => {
          console.log(method, status.code, Date.now() - start + "ms");
          nextStatus(status);
        },
      };
      next(metadata, newListener);
    },
  };
  return new grpc.InterceptingCall(nextCall(options), requester);
};

모범 사례

  • 테이블이 아니라 유스케이스 중심으로 API를 설계하세요.
  • .proto 계약을 잘 문서화하고 패키지에 버전을 붙이세요 (package v1...).
  • 메시지를 작게 유지하고, 필요한 곳에서 스트리밍/백프레셔를 쓰세요.
  • 기본 데드라인과 처음부터 끝까지 일관된 타임아웃을 적용하세요.
  • 헬스 체크(grpc.health.v1.Health)와 readiness probe를 추가하세요.
  • 불일치를 막기 위해 CI에서 스텁 생성을 자동화하세요.

장점 (TL;DR)

  • 서비스 간 통신에서 REST보다 낮은 지연과 더 나은 CPU/네트워크 사용.
  • Proto3로 강하고 진화 가능한 계약.
  • 네이티브 스트리밍과 백프레셔 제어.
  • 성숙한 도구: 인터셉터, 보안, 관측성, 부하 분산.

참고 자료