[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,114 +4,213 @@ title: gRPC and Protocol Buffers
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-DEV-GRPC, gRPC, Protocol Buffers, Protobuf, RPC, 바이너리 통신, 고성능 API]
|
||||
aliases: [gRPC, Protobuf, protocol-buffers]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [API, gRPC, Microservices, Protobuf, Performance, RPC]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [rpc, networking, protobuf, microservices, http2]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: Multi (Go, Rust, TS, Python)
|
||||
framework: gRPC + Protobuf 3 / Edition 2024
|
||||
---
|
||||
|
||||
# [[gRPC와 고성능 바이너리 통신 (gRPC & Protocol Buffers)]]
|
||||
# gRPC and Protocol Buffers
|
||||
|
||||
## 1. 개요
|
||||
gRPC(Google Remote Procedure Call)는 구글에서 개발한 고성능 원격 프로시저 호출 프레임워크이다. HTTP/2 프로토콜과 Protocol Buffers(Protobuf) 직렬화 메커니즘을 기반으로 하며, 마이크로서비스 아키텍처에서 서비스 간의 빠르고 안전한 데이터 교환을 위해 설계되었다.
|
||||
## 매 한 줄
|
||||
> **"매 schema-first IDL + HTTP/2 RPC + binary serialization 의 stack."**. Protocol Buffers 는 2008 Google 공개, gRPC 는 2015 OSS — 매 internal Stubby 의 successor. 매 2026 microservice / cross-language API 의 매 default — 매 REST+JSON 보다 5-10× compact, 매 streaming 매 native, 매 contract 강제.
|
||||
|
||||
## 2. 핵심 기술 스택
|
||||
- **Protocol Buffers (Protobuf)**: 구조화된 데이터를 직렬화하기 위한 언어 중립적, 플랫폼 중립적 방식. XML이나 JSON보다 훨씬 작고 빠르며, `.proto` 파일을 통해 인터페이스를 정의.
|
||||
- **HTTP/2 기반 통신**: 단일 연결을 통한 다중화(Multiplexing), 서버 푸시, 헤더 압축 등을 통해 지연 시간 단축 및 효율적인 리소스 활용.
|
||||
- **양방향 스트리밍**: 클라이언트와 서버가 서로 독립적으로 메시지 스트림을 주고받을 수 있는 전이중 통신 지원.
|
||||
- **코드 생성 (Code Generation)**: 정의된 `.proto` 파일을 바탕으로 다양한 프로그래밍 언어(Go, Java, Python, Node.js 등)의 클라이언트 스텁과 서버 스켈레톤 코드를 자동으로 생성.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 엔지니어링 가치
|
||||
- **압도적인 성능**: 바이너리 직렬화를 사용하여 데이터 크기가 작고 처리 속도가 빨라, 대규모 트래픽이 발생하는 마이크로서비스 간 통신에 최적.
|
||||
- **강력한 타입 안정성**: 컴파일 타임에 타입 체크가 이루어지므로, 런타임 시의 데이터 규격 불일치 에러 방지.
|
||||
- **언어 독립적 협업**: 인터페이스 정의서(.proto) 하나로 서로 다른 언어로 작성된 서비스들이 마치 로컬 함수를 호출하듯 통신 가능.
|
||||
- **자동화된 계약 관리**: 수동으로 API 문서를 작성하는 대신, 소스 코드와 동기화된 인터페이스 정의를 통해 팀 간의 커뮤니케이션 오차 제거.
|
||||
### 매 Protocol Buffers
|
||||
- **Schema**: `.proto` file — 매 message + service 정의.
|
||||
- **Wire format**: tag-length-value, varint encoding — 매 forward/backward compat (unknown field 보존).
|
||||
- **Edition 2024**: `proto2` / `proto3` 의 통합 — 매 explicit feature flag.
|
||||
- **Compiler**: `protoc` + plugin (go, ts-proto, prost, python-betterproto).
|
||||
|
||||
## 4. 트레이드오프 및 주의사항
|
||||
- **브라우저 지원 제약**: 웹 브라우저에서 gRPC를 직접 호출하기 어려우며, 이를 위해 gRPC-Web 프록시나 API Gateway를 통한 변환 과정 필요.
|
||||
- **가독성 저하**: 바이너리 형식이므로 JSON처럼 사람이 눈으로 직접 데이터를 읽고 디버깅하기 어려우며, 전용 도구(grpcurl 등) 활용 필수.
|
||||
- **인프라 설정 복잡성**: HTTP/2 지원을 위해 로드 밸런서, 프록시 서버 등의 인프라 계층에서 추가적인 설정 작업 요구.
|
||||
### 매 gRPC
|
||||
- **Transport**: HTTP/2 — 매 multiplexing, header compression (HPACK).
|
||||
- **4 RPC types**: unary, server-stream, client-stream, bidi-stream.
|
||||
- **Status codes**: 매 `OK`, `INVALID_ARGUMENT`, `UNAUTHENTICATED`, `DEADLINE_EXCEEDED` (16개 표준).
|
||||
- **Deadline**: 매 client → server propagate. 매 RPC chain 매 cumulative.
|
||||
- **Metadata**: 매 trailer/header — auth token, trace.
|
||||
- **gRPC-Web**: 매 browser support (HTTP/1.1 fallback proxy).
|
||||
- **Connect / gRPC-Gateway**: 매 REST+gRPC dual.
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[API_Design_Principles]]: 고성능 서비스 간 통신을 위한 대안 프로토콜.
|
||||
- [[Microservices_Architecture]]: gRPC가 주로 활용되는 아키텍처 환경.
|
||||
- [[Software_Supply_Chain_Security]]: 자동 생성된 SDK 및 라이브러리의 보안 관리.
|
||||
### 매 응용
|
||||
1. Microservice internal RPC.
|
||||
2. Mobile ↔ backend (Square, Netflix).
|
||||
3. Service mesh (Envoy, Istio).
|
||||
4. Streaming (live ML inference, IoT).
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 초저지연 통신과 엄격한 타입 안정성을 바탕으로 마이크로서비스 간의 효율적인 유기적 결합을 달성하기 위한 gRPC 및 바이너리 직렬화 표준 정립.
|
||||
## 💻 패턴
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
### .proto schema
|
||||
```protobuf
|
||||
edition = "2024";
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
package shop.v1;
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
option go_package = "github.com/example/shop/v1;shopv1";
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
service Catalog {
|
||||
rpc GetProduct(GetProductRequest) returns (Product);
|
||||
rpc StreamUpdates(StreamUpdatesRequest) returns (stream ProductUpdate);
|
||||
rpc UploadImages(stream Image) returns (UploadAck);
|
||||
rpc Chat(stream ChatMsg) returns (stream ChatMsg);
|
||||
}
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
message GetProductRequest {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
message Product {
|
||||
string id = 1;
|
||||
string name = 2;
|
||||
int64 price_cents = 3;
|
||||
repeated string tags = 4;
|
||||
google.protobuf.Timestamp updated_at = 5;
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Go server (unary + stream)
|
||||
```go
|
||||
type catalogServer struct{ shopv1.UnimplementedCatalogServer }
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
func (s *catalogServer) GetProduct(ctx context.Context, req *shopv1.GetProductRequest) (*shopv1.Product, error) {
|
||||
if req.Id == "" {
|
||||
return nil, status.Error(codes.InvalidArgument, "id required")
|
||||
}
|
||||
p, err := s.db.Find(ctx, req.Id)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, status.Error(codes.NotFound, "product missing")
|
||||
}
|
||||
return p, err
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
func (s *catalogServer) StreamUpdates(req *shopv1.StreamUpdatesRequest, srv shopv1.Catalog_StreamUpdatesServer) error {
|
||||
for ev := range s.bus.Subscribe(srv.Context()) {
|
||||
if err := srv.Send(ev); err != nil { return err }
|
||||
}
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### TS client (ts-proto + grpc-js)
|
||||
```typescript
|
||||
import { credentials } from '@grpc/grpc-js';
|
||||
import { CatalogClient } from './gen/shop/v1/catalog';
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
const client = new CatalogClient('catalog:50051', credentials.createSsl());
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
const p = await client.getProduct({ id: 'sku-42' }, { deadline: Date.now() + 1000 });
|
||||
console.log(p.name);
|
||||
|
||||
// streaming
|
||||
const stream = client.streamUpdates({});
|
||||
stream.on('data', (u) => console.log('update', u));
|
||||
stream.on('error', (e) => console.error(e));
|
||||
```
|
||||
|
||||
### Deadline propagation
|
||||
```go
|
||||
ctx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
||||
defer cancel()
|
||||
// 매 outgoing RPC 매 자동 deadline 전달.
|
||||
resp, err := downstream.Sub(ctx, req)
|
||||
```
|
||||
|
||||
### Interceptor (auth + tracing)
|
||||
```go
|
||||
func authUnary(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
md, _ := metadata.FromIncomingContext(ctx)
|
||||
tok := md.Get("authorization")
|
||||
if len(tok) == 0 { return nil, status.Error(codes.Unauthenticated, "no token") }
|
||||
user, err := verify(tok[0])
|
||||
if err != nil { return nil, status.Error(codes.Unauthenticated, "bad token") }
|
||||
return handler(context.WithValue(ctx, userKey{}, user), req)
|
||||
}
|
||||
|
||||
s := grpc.NewServer(grpc.UnaryInterceptor(authUnary))
|
||||
```
|
||||
|
||||
### gRPC-Web (browser)
|
||||
```typescript
|
||||
import { createPromiseClient } from '@connectrpc/connect';
|
||||
import { createGrpcWebTransport } from '@connectrpc/connect-web';
|
||||
import { Catalog } from './gen/shop/v1/catalog_connect';
|
||||
|
||||
const transport = createGrpcWebTransport({ baseUrl: 'https://api.example.com' });
|
||||
const client = createPromiseClient(Catalog, transport);
|
||||
const p = await client.getProduct({ id: 'sku-42' });
|
||||
```
|
||||
|
||||
### Buf for build + lint
|
||||
```yaml
|
||||
# buf.yaml
|
||||
version: v2
|
||||
modules:
|
||||
- path: proto
|
||||
lint:
|
||||
use: [DEFAULT]
|
||||
breaking:
|
||||
use: [FILE]
|
||||
```
|
||||
```bash
|
||||
buf lint
|
||||
buf breaking --against '.git#branch=main'
|
||||
buf generate
|
||||
```
|
||||
|
||||
### Backward-compat 규칙
|
||||
```protobuf
|
||||
message Product {
|
||||
string id = 1;
|
||||
string name = 2;
|
||||
// 매 deprecated 후에도 number 재사용 X
|
||||
reserved 3;
|
||||
reserved "old_price";
|
||||
int64 price_cents = 4;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 매 internal microservice | gRPC unary + interceptor |
|
||||
| 매 browser client | Connect / gRPC-Web |
|
||||
| 매 public open API | REST/JSON or gRPC-Gateway dual |
|
||||
| 매 streaming (logs, ML) | server-stream / bidi |
|
||||
| 매 mobile (cellular flaky) | gRPC + retry interceptor + deadline |
|
||||
|
||||
**기본값**: 매 internal = gRPC, 매 external = Connect (dual REST + gRPC).
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[RPC]] · [[Serialization]] · [[HTTP2]]
|
||||
- 변형: [[Connect_RPC]] · [[Thrift]] · [[Cap_n_Proto]] · [[FlatBuffers]]
|
||||
- 응용: [[Service_Mesh]] · [[Microservices]] · [[Envoy]]
|
||||
- Adjacent: [[Buf]] · [[OpenAPI]] · [[GraphQL]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 cross-language API, 매 streaming, 매 strict contract.
|
||||
**언제 X**: 매 simple browser CRUD (REST 충분), 매 ad-hoc tooling (JSON 직관적).
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Field number 재사용**: 매 wire-incompatible — 매 reserved 의 사용.
|
||||
- **매 required 다용**: 매 schema evolution 차단 — proto3 default optional 유지.
|
||||
- **매 deadline 미설정**: 매 server cascade hang.
|
||||
- **매 large message (>4MB)**: 매 default limit hit — 매 stream 으로 분할.
|
||||
- **매 .proto 의 versioning X**: 매 `v1`, `v2` package 분리 mandatory.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (grpc.io docs, protobuf.dev Edition 2024 spec, Buf docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — gRPC patterns, Edition 2024, Connect-RPC |
|
||||
|
||||
Reference in New Issue
Block a user