콘텐츠로 이동

NestJS Web Push Notification: Socket.IO와 Redis로 실시간 알림 구현

Interactive Diagram

새 탭 ↗

실시간 알림(Web Push)은 WebSocket 기반으로 구현하고, 사용자 연결 상태는 Redis에 캐싱한다. NestJS는 Socket.IO를 Gateway 패턴으로 통합 지원하므로, WebSocket lifecycle과 event를 선언적으로 관리할 수 있다. 이 글은 Socket.IO Gateway 구현, Redis 기반 사용자 세션 관리, Socket.IO Admin UI 구성을 다룬다.

Terminal window
npm i --save @nestjs/websockets @nestjs/platform-socket.io
  • 디렉터리src/
    • 디렉터리events/
      • events.gateway.ts
      • events.module.ts

Client side가 NestJS Gateway 두 개에 연결되고 Gateway가 Value, Service, Provider, Component를 주입받는 구조 출처: NestJS 문서, Gateways, Kamil Mysliwiec and NestJS contributors, MIT

events.gateway.ts
import {
SubscribeMessage,
WebSocketGateway,
OnGatewayInit,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
ConnectedSocket,
MessageBody,
} from '@nestjs/websockets';
import { Socket, Server } from 'socket.io';
import { Logger } from '@nestjs/common';
import { instrument } from '@socket.io/admin-ui';
@WebSocketGateway({
cors: {
origin: [
'https://admin.socket.io',
'https://socketio-admin.example.com',
'http://localhost:8080',
],
credentials: true,
},
})
export class EventsGateway
implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
@WebSocketServer() server: Server;
private logger: Logger = new Logger('EventsGateway');
afterInit(server: Server) {
this.logger.log(`WebSocket initialized: ${server.path()}`);
instrument(server, {
auth: false, // Admin UI 인증 비활성화 (테스트용)
});
}
handleConnection(client: Socket, ...args: any[]) {
this.logger.log(`Client connected: ${client.id}`);
}
handleDisconnect(client: Socket) {
this.logger.log(`Client disconnected: ${client.id}`);
}
}

핵심 interface:

  • OnGatewayInit: WebSocket 서버 초기화 후 실행 (afterInit)
  • OnGatewayConnection: 클라이언트 연결 시 실행 (handleConnection)
  • OnGatewayDisconnect: 클라이언트 연결 해제 시 실행 (handleDisconnect)
cors: {
origin: [
'https://admin.socket.io', // Public Admin UI
'https://socketio-admin.example.com', // Self-hosted Admin UI
'http://localhost:8080', // 개발 환경
],
credentials: true,
}

Socket.IO Admin UI를 사용하려면 origin에 Admin UI URL을 포함해야 한다.

import { UserSessionCache } from './user-session.cache';
@WebSocketGateway({...})
export class EventsGateway ... {
constructor(private userSessionCache: UserSessionCache) {}
@SubscribeMessage('patientJoin')
async joinRoom(
@ConnectedSocket() client: Socket,
@MessageBody() userName: string,
) {
// 1. Redis에 사용자 정보와 socketId 저장
this.userSessionCache.addOrUpdate(userName, client.id);
// 2. Active 사용자 목록 조회
const activeUsers = await this.userSessionCache.getAllActive();
const adminUser = await this.userSessionCache.getAdminActive();
// 3. Admin 사용자에게만 전체 사용자 목록 전송
this.server.to(adminUser.socketId).emit(
'patientList',
activeUsers.map((x) => x.userName),
);
// 4. 각 사용자에게 등록 완료 알림 전송
activeUsers.forEach((user) => {
this.server.to(user.socketId).emit(user.userName + ':registered');
});
}
}

Workflow:

  1. Frontend가 'patientJoin' event를 emit
  2. Gateway가 event를 subscribe
  3. Redis에 사용자 정보 + socketId 저장 또는 업데이트
  4. Admin 사용자의 socketId로 전체 active 사용자 목록 전송
  5. 각 active 사용자의 socketId로 개별 알림 전송
Decorator용도
@SubscribeMessage('eventName')특정 event를 listen하는 handler 정의
@ConnectedSocket()Socket 연결 정보(client.id 등) 주입
@MessageBody()Event payload(data) 주입
@WebSocketServer()Socket.IO Server 인스턴스 주입
// 특정 socketId로 전송
this.server.to(socketId).emit('eventName', data);
// 모든 클라이언트에게 전송
this.server.emit('eventName', data);
// 특정 room에 전송
this.server.to('roomName').emit('eventName', data);
import { Injectable, Inject, CACHE_MANAGER } from '@nestjs/common';
import { Cache } from 'cache-manager';
import * as moment from 'moment';
interface UserSession {
userName: string;
lastConnectedTime: string;
socketId: string;
}
@Injectable()
export class UserSessionCache {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async addOrUpdate(userName: string, socketId: string): Promise<void> {
const session: UserSession = {
userName,
lastConnectedTime: moment().format('YYYY-MM-DDTHH:mm:ss'),
socketId,
};
await this.cacheManager.set(`user:${userName}`, session, { ttl: 300 }); // 5분 TTL
}
async getAllActive(): Promise<UserSession[]> {
const keys = await this.cacheManager.store.keys('user:*');
const sessions: UserSession[] = [];
for (const key of keys) {
const session = await this.cacheManager.get<UserSession>(key);
if (session && this.isActive(session)) {
sessions.push(session);
}
}
return sessions;
}
async getAdminActive(): Promise<UserSession> {
return await this.cacheManager.get<UserSession>('user:admin');
}
private isActive(session: UserSession): boolean {
const lastConnected = moment(session.lastConnectedTime);
const now = moment();
return now.diff(lastConnected, 'seconds') < 60; // 60초 이내 활동
}
}

핵심 로직:

  • addOrUpdate: 사용자 이름과 socketId를 Redis에 저장, lastConnectedTime 갱신
  • getAllActive: Redis의 모든 user:* key를 조회하고, lastConnectedTime이 60초 이내인 사용자만 반환
  • getAdminActive: Admin 사용자(고정된 username admin)의 세션 조회
[
{
"userName": "admin",
"lastConnectedTime": "2022-08-03T06:53:20",
"socketId": "8dvBgASLXbMkv2i4AAAL"
},
{
"userName": "Christian Dior",
"lastConnectedTime": "2022-08-03T06:52:20",
"socketId": "enOuMMdNJtna6WnZAAAH"
},
{
"userName": "Coco Chanel",
"lastConnectedTime": "2022-08-03T07:00:04",
"socketId": "ndQXCVnn0ziFEoqCAAAN"
}
]

Socket.IO Admin UI: 연결 상태 모니터링

섹션 제목: “Socket.IO Admin UI: 연결 상태 모니터링”
Terminal window
npm i --save @socket.io/admin-ui
import { instrument } from '@socket.io/admin-ui';
@WebSocketGateway({
cors: {
origin: [
'https://admin.socket.io',
'https://socketio-admin.example.com',
],
credentials: true,
},
})
export class EventsGateway implements OnGatewayInit, ... {
afterInit(server: Server) {
this.logger.log(`WebSocket initialized: ${server.path()}`);
instrument(server, {
auth: false, // 인증 비활성화 (개발용)
// auth: {
// type: "basic",
// username: "admin",
// password: "admin123"
// }
});
}
}

Socket.IO 공식 Admin UI에서 서버 URL을 입력하면 바로 모니터링 가능하다.

보안 주의:

  • Public Admin UI는 누구나 접속할 수 있으므로, 개발 환경에서만 사용
  • 운영 환경에서는 반드시 auth 설정 또는 Self-hosted Admin UI 사용

Socket.IO Admin UI 소스를 clone해서 직접 hosting한다.

Terminal window
git clone https://github.com/socketio/socket.io-admin-ui.git
cd socket.io-admin-ui
npm install
npm run build
# dist 폴더를 static hosting

Static 파일만으로 hosting 가능하므로, Nginx나 S3 + CloudFront로 배포할 수 있다.

  • Socket 연결 상태 모니터링: 현재 연결된 클라이언트 수, socketId 목록
  • Event 전송 테스트: Admin UI에서 특정 event를 직접 emit
  • Server 상태 모니터링: 메모리 사용량, uptime, transport 방식
  • Namespace 조회: /, /admin 같은 namespace별 클라이언트 목록
  • socketId를 Redis에 저장: 사용자별로 메시지를 보내려면 socketId가 필요하다
  • lastConnectedTime으로 active 판단: Redis TTL만으로는 부족하고, 마지막 활동 시간 기준이 필요하다
  • Admin 사용자는 고정 username: 전체 사용자 목록을 받을 권한이 있는 사용자를 구분한다
  • Admin UI는 auth 설정 필수: 운영 환경에서 인증 없이 열어두면 보안 사고로 직결된다
  • CORS를 명확히 설정: Admin UI origin을 포함하지 않으면 Admin UI에서 연결이 안 된다
Terminal window
### WebSocket 서버 초기화
[Winston] Info 2022-08-03T06:24:19+00:00 WebSocket initialized: /socket.io
### 클라이언트 연결/해제
[Winston] Info 2022-08-03T06:32:51+00:00 Client connected: 8dvBgASLXbMkv2i4AAAL
[Winston] Info 2022-08-03T06:58:15+00:00 Client disconnected: enOuMMdNJtna6WnZAAAH
[Winston] Info 2022-08-03T06:58:15+00:00 Client connected: ndQXCVnn0ziFEoqCAAAN

이 Web Push 구조를 Upstream/Downstream 프로세스와 통합하는 설계는 NestJS Upstream/Downstream 설계에서 다룬다.