NestJS Web Push Notification: Socket.IO와 Redis로 실시간 알림 구현
실시간 알림(Web Push)은 WebSocket 기반으로 구현하고, 사용자 연결 상태는 Redis에 캐싱한다. NestJS는 Socket.IO를 Gateway 패턴으로 통합 지원하므로, WebSocket lifecycle과 event를 선언적으로 관리할 수 있다. 이 글은 Socket.IO Gateway 구현, Redis 기반 사용자 세션 관리, Socket.IO Admin UI 구성을 다룬다.
Socket.IO 설치
섹션 제목: “Socket.IO 설치”npm i --save @nestjs/websockets @nestjs/platform-socket.ioWebSocket Gateway 구조
섹션 제목: “WebSocket Gateway 구조”디렉터리src/
디렉터리events/
- events.gateway.ts
- events.module.ts

events.gateway.ts
섹션 제목: “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 설정
섹션 제목: “CORS 설정”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을 포함해야 한다.
Event Subscribe & Emit
섹션 제목: “Event Subscribe & Emit”사용자 등록 Event
섹션 제목: “사용자 등록 Event”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:
- Frontend가
'patientJoin'event를 emit - Gateway가 event를 subscribe
- Redis에 사용자 정보 + socketId 저장 또는 업데이트
- Admin 사용자의 socketId로 전체 active 사용자 목록 전송
- 각 active 사용자의 socketId로 개별 알림 전송
Event Decorator 설명
섹션 제목: “Event Decorator 설명”| Decorator | 용도 |
|---|---|
@SubscribeMessage('eventName') | 특정 event를 listen하는 handler 정의 |
@ConnectedSocket() | Socket 연결 정보(client.id 등) 주입 |
@MessageBody() | Event payload(data) 주입 |
@WebSocketServer() | Socket.IO Server 인스턴스 주입 |
Socket Emit 방식
섹션 제목: “Socket Emit 방식”// 특정 socketId로 전송this.server.to(socketId).emit('eventName', data);
// 모든 클라이언트에게 전송this.server.emit('eventName', data);
// 특정 room에 전송this.server.to('roomName').emit('eventName', data);Redis 기반 사용자 세션 관리
섹션 제목: “Redis 기반 사용자 세션 관리”UserSessionCache 구조
섹션 제목: “UserSessionCache 구조”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)의 세션 조회
Redis 데이터 예시
섹션 제목: “Redis 데이터 예시”[ { "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: 연결 상태 모니터링”npm i --save @socket.io/admin-uiGateway에 Admin UI 활성화
섹션 제목: “Gateway에 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" // } }); }}Admin UI 사용 방법
섹션 제목: “Admin UI 사용 방법”1. Public Admin UI (https://admin.socket.io)
섹션 제목: “1. Public Admin UI (https://admin.socket.io)”Socket.IO 공식 Admin UI에서 서버 URL을 입력하면 바로 모니터링 가능하다.
보안 주의:
- Public Admin UI는 누구나 접속할 수 있으므로, 개발 환경에서만 사용
- 운영 환경에서는 반드시 auth 설정 또는 Self-hosted Admin UI 사용
2. Self-hosted Admin UI
섹션 제목: “2. Self-hosted Admin UI”Socket.IO Admin UI 소스를 clone해서 직접 hosting한다.
git clone https://github.com/socketio/socket.io-admin-ui.gitcd socket.io-admin-uinpm installnpm run build# dist 폴더를 static hostingStatic 파일만으로 hosting 가능하므로, Nginx나 S3 + CloudFront로 배포할 수 있다.
Admin UI 기능
섹션 제목: “Admin UI 기능”- 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에서 연결이 안 된다
연결 로그 예시
섹션 제목: “연결 로그 예시”### 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 설계에서 다룬다.