project/NestJS + Kubernetes & 마이크로서비스 배포

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드 - NestJS 실시간 기능 설계: WebSocket + GraphQL Subscriptions

octo54 2025. 4. 10. 10:41
반응형

📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드

9. NestJS 실시간 기능 설계: WebSocket + GraphQL Subscriptions


현대 웹 애플리케이션에서는 실시간 데이터 처리가 필수가 되었습니다.
NestJS는 WebSocket, GraphQL Subscriptions, Redis Pub/Sub 등을 통해 다양한 실시간 기능을 손쉽게 구현할 수 있습니다.
이번 글에서는 NestJS에서 실시간 채팅, 알림, 대시보드 업데이트와 같은 기능을 구축하기 위한 실전 전략을 소개합니다. 🚀


✅ 1. 실시간 기능이 필요한 이유

  • 실시간 채팅, 협업 툴, 게임
  • 대시보드 지표 자동 갱신
  • 실시간 알림(Notification) 기능
  • IoT 디바이스 상태 모니터링

💡 REST API는 클라이언트가 주기적으로 polling해야 하므로 비효율적
→ WebSocket or Subscription 기반의 push 구조로 개선 필요


✅ 2. NestJS에서 지원하는 실시간 기술

기술 설명 장점

WebSocket (Socket.IO) 양방향 통신, 클라이언트 ↔ 서버 직접 연결 간단하고 빠름
GraphQL Subscriptions GraphQL 기반 실시간 데이터 스트림 GraphQL API와 통합 용이
Redis Pub/Sub 다중 인스턴스 간 메시지 브로드캐스트 스케일아웃에 유리

✅ 3. WebSocket (Socket.IO) 기반 실시간 통신

✅ 1) 설치 및 설정

npm install @nestjs/websockets @nestjs/platform-socket.io

📂 chat.gateway.ts

@WebSocketGateway({ cors: true })
export class ChatGateway {
  @WebSocketServer() server: Server;

  @SubscribeMessage('chat')
  handleChat(@MessageBody() msg: string): void {
    this.server.emit('chat', msg);
  }
}

✅ 2) 클라이언트 예제 (HTML + JS)

<script src="/socket.io/socket.io.js"></script>
<script>
  const socket = io('http://localhost:3000');
  socket.emit('chat', '안녕하세요!');
  socket.on('chat', msg => console.log('메시지:', msg));
</script>

✅ 4. GraphQL Subscriptions 기반 실시간 설계

✅ 1) 설치

npm install @nestjs/graphql graphql graphql-subscriptions graphql-ws

✅ 2) 설정

📂 app.module.ts

GraphQLModule.forRoot({
  autoSchemaFile: true,
  subscriptions: {
    'graphql-ws': true,
  },
})

✅ 3) 실시간 알림 예제

📂 notifications.resolver.ts

@Resolver()
export class NotificationResolver {
  constructor(@Inject('PUB_SUB') private pubSub: PubSub) {}

  @Mutation(() => String)
  sendNotification(): string {
    this.pubSub.publish('notificationAdded', {
      notificationAdded: '새로운 알림!',
    });
    return '보냄';
  }

  @Subscription(() => String)
  notificationAdded() {
    return this.pubSub.asyncIterator('notificationAdded');
  }
}

✅ 클라이언트에서 subscription { notificationAdded } 를 구독하면 서버에서 알림 push


✅ 5. Redis 기반 Pub/Sub 설계 (멀티 인스턴스 대응)

📂 pubsub.module.ts

const redisOptions = {
  host: 'localhost',
  port: 6379,
};

@Module({
  providers: [
    {
      provide: 'PUB_SUB',
      useFactory: () => new RedisPubSub({ connection: redisOptions }),
    },
  ],
  exports: ['PUB_SUB'],
})
export class PubSubModule {}

💡 서버가 여러 개일 때, Redis Pub/Sub을 사용하면 메시지를 모든 인스턴스에 브로드캐스트 가능!


✅ 6. 실전 구현 시 고려사항

항목 내용

인증 JWT 또는 세션 기반 인증 적용 (socket.handshake)
메시지 보안 메시지 내용 암호화 또는 권한 검증 필요
확장성 Redis Pub/Sub 또는 Kafka 활용
연결 수 관리 WebSocket 연결 수 모니터링 + 제한 적용 (Rate Limit)
대체 전략 polling fallback → 오래된 브라우저 고려

✅ 7. 실시간 기능 + Kubernetes 연동 팁

  • Ingress 설정: WebSocket 사용 시 nginx.ingress.kubernetes.io/backend-protocol: "WS" 추가 필요
  • Sticky Session: 클러스터 환경에서 특정 사용자 연결 유지 필요 시
  • Redis Pod 별도 운영: 실시간 메시징은 Redis 의존도가 높으므로 모니터링 중요

✅ 결론: NestJS로 실시간 시스템 설계 마스터하기

✅ WebSocket을 활용한 실시간 양방향 통신
✅ GraphQL Subscriptions로 GraphQL API 내 실시간 기능 구현
✅ Redis를 통한 브로드캐스트 및 스케일아웃
✅ Kubernetes에서도 실시간 통신 안정적으로 운영 가능

다음 글에서는 NestJS 프로젝트에서 관찰성(Observability)을 높이는 방법 – OpenTelemetry, Distributed Tracing, 로그 수집 전략을 다룹니다! 🔍


🔍 다음 글 예고: NestJS Observability – 로그, 추적, 지표 통합 전략

📌 다음 편: 10. NestJS Observability: 로그, 모니터링, 추적 통합 가이드


 

NestJS WebSocket,NestJS 실시간 기능,NestJS GraphQL Subscriptions,NestJS Redis PubSub,NestJS 실시간 채팅,NestJS 알림 기능,NestJS 소켓 설정,NestJS 실시간 대시보드,NestJS 서버 푸시,NestJS 실시간 통신