0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

切れない・遅れないWebSocket!マイクロサービス時代を生き抜くリアルタイム通信の最適解

0
Last updated at Posted at 2026-11-28

ある日、ユーザーから「チャットのメッセージが全く届かない」と緊急報告が入った。慌ててログを確認すると、APIゲートウェイとクライアント間のWebSocket接続が頻繁に切断され、その後の自動再接続処理も追いついていない状況が浮かび上がった。結果として、顧客対応に追われる事態となり、リアルタイム通信の信頼性の低さがチーム全体の大きな課題として浮上した。マイクロサービスが当たり前となった現代において、安易なWebSocket実装は、ネットワークの不安定性やサーバー負荷変動に弱く、すぐにシステム障害に繋がりかねない。

本記事では、この課題を解決するため、TypeScriptを用いたモダンなWebアプリケーションにおけるWebSocketの堅牢な実装方法を深掘りする。特に、JWT認証に基づくセキュアな接続確立、接続断への耐性を高めるクライアント側の自動再接続(ReconnectStrategy)やSocket.IOのハートビートによる死活監視、さらにメッセージバッファリング技術、そしてサーバー側の疎結合な接続管理(ConnectionManager, RealtimeService, WebSocketGateway)に焦点を当てる。ユーザーのプレゼンス管理機能を例に、フロントエンドからバックエンドまで一貫した設計思想で、インフラ/NWの制約やセキュリティ要件を考慮した「切れない・遅れない」リアルタイム通信の最適解を提示する。

課題・背景

APIゲートウェイとクライアント間のWebSocket接続が頻繁に切断され、その後の再接続処理も追いついていない状況は、ネットワークインフラ、マイクロサービスアーキテクチャ、セキュリティ、そしてクライアント挙動という多層的な要因が複雑に絡み合った結果です。単なるコードバグでは片付けられない、根深い問題の正体を解き明かします。

頻繁な切断を誘発するネットワークインフラの挙動

多くのWebアプリケーションにおいて、クライアントとバックエンドの間にはL7ロードバランサーやAPIゲートウェイ、ファイアウォールが介在します。これらはHTTP/1.1のような短期的なリクエスト-レスポンスサイクルを前提に設計されており、アイドル状態が一定時間続くとTCPセッションを切断する「アイドルタイムアウト」が設定されています(例: AWS ALBのデフォルト60秒)。WebSocketは長時間接続を維持するため、アプリケーション側で能動的なハートビートを送信しない限り、これらのタイムアウトに抵触し、意図しない接続切断が発生します。このネットワーク機器による切断は正常な挙動ですが、適切にハンドリングできなければ、ユーザーは「メッセージが届かない」といった致命的な体験に直面します。

マイクロサービスアーキテクチャがもたらす複雑性

モノリシックなアプリケーションであればWebSocket接続管理は単純でしたが、マイクロサービスアーキテクチャでは、複数の RealtimeService が存在し、クライアントからの接続は WebSocketGateway を経由していずれかのサービスにルーティングされます。この際、特定のクライアントがどのサービスに接続されているかという状態を、ConnectionManager のようなサービスが共有・管理する必要があります。再接続時、APIゲートウェイが別の RealtimeService インスタンスにルーティングする可能性があり、古いサービスに残った接続情報との不整合や、新しいサービスが以前のセッション情報を引き継げず、プレゼンス情報が適切に更新されない事態に陥ります。多数のサービスインスタンス間でステートフルなWebSocket接続を疎結合に保ち、スケーラビリティを確保することは大きな課題です。

セキュリティと認証認可の課題

WebSocket接続は初回時にJWTなどの認証トークンを用いて認証されますが、これは接続確立時の JwtWsAuthGuard による検証と、以降の各メッセージに対するガードを通じて行われます。JWTには有効期限があり、WebSocket接続が長時間維持される間に期限が切れると、その接続はもはや正当な認証状態ではありません。アプリケーションがこれを検知せず通信を続けると、不正アクセスやデータ漏洩のリスクを抱えます。再接続時、クライアントは新しいJWTトークンを取得して認証し直す必要がありますが、このプロセスに不備があると、古い期限切れトークンを使い続けて認証エラーの無限ループに陥ったり、サーバー側で強制切断されたりします。最小権限の原則に則り、セッション中にユーザーの権限が変更された場合に動的にWebSocket接続の認可状態を更新する仕組みも不可欠です。

これらの多層的な課題を放置すれば、単なるメッセージ不達に留まらず、ユーザーからの信頼失墜、運用コストの増大、さらにはセキュリティインシデントへと発展するリスクを常に抱えることになります。リアルタイム通信の「切れない」「遅れない」を実現するためには、ネットワーク、インフラ、アーキテクチャ、セキュリティ、そしてクライアント側の挙動という、あらゆる側面からの包括的なアプローチが不可欠なのです。

実践・解決策

頻繁なWebSocket切断と再接続の失敗という喫緊の課題に対し、堅牢なリアルタイム通信基盤を再構築するためには、フロントエンドとバックエンド双方で設計思想を一新する必要があります。

サーバー側の実装

1. JWT認証によるセキュアなWebSocket接続の確立 (JwtWsAuthGuard)

// src/auth/jwt-ws.guard.ts
import { CanActivate, ExecutionContext, Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Observable } from 'rxjs';
import { Socket } from 'socket.io';

@Injectable()
export class JwtWsAuthGuard implements CanActivate {
  private readonly logger = new Logger(JwtWsAuthGuard.name);

  constructor(private readonly jwtService: JwtService) {}

  canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
    const client: Socket = context.switchToWs().getClient();
    // ヘッダーまたはクエリパラメータからトークンを取得する実装を想定
    // 例えば、クライアントが `ws://localhost?token=YOUR_JWT` のように接続する場合
    const token = client.handshake.auth?.token || client.handshake.query?.token;

    if (!token || typeof token !== 'string') {
      this.logger.warn(`Unauthenticated WebSocket connection attempt: No token provided.`);
      client.disconnect(true); // 認証失敗時は強制切断
      return false;
    }

    try {
      const payload = this.jwtService.verify(token);
      // 認証成功時、ソケットインスタンスにユーザー情報を付与
      // これにより、以降のイベントハンドラで `client.user` としてアクセス可能
      client.data.user = payload;
      return true;
    } catch (error) {
      this.logger.error(`WebSocket JWT verification failed: ${(error as Error).message}`);
      client.disconnect(true); // 認証失敗時は強制切断
      return false;
    }
  }
}

2. WebSocketGateway:接続と認証のインターフェース

// src/realtime/websocket.gateway.ts
import {
  WebSocketGateway,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketServer,
  MessageBody,
  ConnectedSocket,
} from '@nestjs/websockets';
import { UseGuards, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Server, Socket } from 'socket.io';
import { JwtWsAuthGuard } from '../auth/jwt-ws.guard';
import { ConnectionManager } from './connection.manager';
import { RealtimeService } from './realtime.service';

// WebSocketのポートとCORS設定
// ※ origin: '*' と credentials: true の組み合わせはブラウザに拒否されるため、
//    フロントエンドのオリジンを明示する
@WebSocketGateway({
  cors: {
    origin: process.env.FRONTEND_ORIGIN ?? 'http://localhost:3000',
    credentials: true,
  },
  // Socket.IOのエンジンレベルハートビート。10秒ごとのpingが
  // ALBの60秒アイドルタイムアウトを下回るため、アプリ独自のping/pongは不要
  pingInterval: 10000, // クライアントへのping間隔 (ms)
  pingTimeout: 5000,   // クライアントからのpongを待つ時間 (ms)
})
// 注意: @UseGuards は @SubscribeMessage ハンドラに適用され、
// 接続確立時 (handleConnection) には実行されない。
// そのため接続時の認証は handleConnection 内でトークンを直接検証する
@UseGuards(JwtWsAuthGuard)
export class AppWebSocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer() server!: Server;
  private readonly logger = new Logger(AppWebSocketGateway.name);

  constructor(
    private readonly connectionManager: ConnectionManager,
    private readonly realtimeService: RealtimeService,
    private readonly jwtService: JwtService,
  ) {}

  // 新しいWebSocket接続が確立された際に呼ばれる
  async handleConnection(@ConnectedSocket() client: Socket, ...args: any[]) {
    // ガードは接続時には実行されないため、ここでトークンを直接検証する。
    // client.data.user が設定されるのはこの検証が通った場合のみで、
    // 検証なしに user.sub を参照すると未認証の接続で例外が発生する
    const token = client.handshake.auth?.token || client.handshake.query?.token;
    if (!token || typeof token !== 'string') {
      this.logger.warn(`Rejected unauthenticated WebSocket connection: ${client.id}`);
      client.disconnect(true);
      return;
    }
    try {
      client.data.user = this.jwtService.verify(token);
    } catch (error) {
      this.logger.warn(`Rejected WebSocket connection with invalid token: ${client.id} (${(error as Error).message})`);
      client.disconnect(true);
      return;
    }
    const user = client.data.user;
    this.logger.log(`Client connected: ${client.id} (User: ${user.sub})`); // subはJWTのsubject(ユーザーIDなど)

    this.connectionManager.addConnection(user.sub, client.id);
    this.realtimeService.updateUserPresence(user.sub, 'online'); // ユーザーをオンライン状態に更新
    this.server.emit('presence_update', { userId: user.sub, status: 'online' }); // 全員にプレゼンス更新を通知
  }

  // WebSocket接続が切断された際に呼ばれる
  async handleDisconnect(@ConnectedSocket() client: Socket) {
    const user = client.data.user;
    if (!user) {
      // 認証ガードを通過できなかった接続、またはユーザー情報がない場合は処理しない
      this.logger.warn(`Disconnected unauthenticated or unknown client: ${client.id}`);
      return;
    }

    this.logger.log(`Client disconnected: ${client.id} (User: ${user.sub})`);
    this.connectionManager.removeConnection(user.sub, client.id);

    // そのユーザーの全ての接続が切断された場合のみ、オフライン状態に更新
    if (!this.connectionManager.getUserConnections(user.sub).size) {
      this.realtimeService.updateUserPresence(user.sub, 'offline');
      this.server.emit('presence_update', { userId: user.sub, status: 'offline' });
    }
  }

  // クライアントからのプレゼンス更新イベントを購読
  @SubscribeMessage('update_presence')
  handlePresenceUpdate(
    @ConnectedSocket() client: Socket,
    @MessageBody() payload: { status: 'online' | 'away' | 'offline' },
  ) {
    const user = client.data.user;
    this.logger.debug(`User ${user.sub} updated presence to: ${payload.status}`);
    this.realtimeService.updateUserPresence(user.sub, payload.status);
    this.server.emit('presence_update', { userId: user.sub, status: payload.status });
  }
}

3. ConnectionManager:接続状態の管理とスケーラビリティ

// src/realtime/connection.manager.ts
import { Injectable, Logger } from '@nestjs/common';
// import { RedisService } from 'nestjs-redis'; // Redisを利用する場合

@Injectable()
export class ConnectionManager {
  private readonly logger = new Logger(ConnectionManager.name);
  // Map<userId, Set<socketId>>: 1ユーザーが複数のデバイスから接続するケースに対応
  private userConnections = new Map<string, Set<string>>();
  // private socketToUser = new Map<string, string>(); // socketIdからuserIdを逆引きする場合に利用

  // constructor(private readonly redisService: RedisService) {} // Redisを利用する場合

  addConnection(userId: string, socketId: string) {
    if (!this.userConnections.has(userId)) {
      this.userConnections.set(userId, new Set<string>());
    }
    this.userConnections.get(userId)!.add(socketId);
    // this.socketToUser.set(socketId, userId); // 逆引き用

    // Redisなどに接続情報をPublishする(複数インスタンスでのスケーリング時)
    // await this.redisService.getClient().publish('websocket_connections', JSON.stringify({ type: 'add', userId, socketId }));
    this.logger.debug(`Connection added: User ${userId}, Socket ${socketId}`);
  }

  removeConnection(userId: string, socketId: string) {
    if (this.userConnections.has(userId)) {
      this.userConnections.get(userId)!.delete(socketId);
      if (this.userConnections.get(userId)!.size === 0) {
        this.userConnections.delete(userId);
      }
    }
    // this.socketToUser.delete(socketId); // 逆引き用

    // Redisなどに接続情報をPublishする
    // await this.redisService.getClient().publish('websocket_connections', JSON.stringify({ type: 'remove', userId, socketId }));
    this.logger.debug(`Connection removed: User ${userId}, Socket ${socketId}`);
  }

  getUserConnections(userId: string): Set<string> {
    return this.userConnections.get(userId) || new Set<string>();
  }

  // 特定のユーザーにメッセージを送信するヘルパー (Gatewayから呼び出される)
  getSocketIdsForUser(userId: string): string[] {
    return Array.from(this.userConnections.get(userId) || []);
  }

  // 全ての接続済みユーザーIDを取得する (例: オンラインユーザーリスト表示用)
  getAllConnectedUsers(): string[] {
    return Array.from(this.userConnections.keys());
  }
}

4. RealtimeService:プレゼンス管理のビジネスロジック

// src/realtime/realtime.service.ts
import { Injectable, Logger } from '@nestjs/common';
// import { UserRepository } from '../users/user.repository'; // ユーザーの永続化を担当するリポジトリ

@Injectable()
export class RealtimeService {
  private readonly logger = new Logger(RealtimeService.name);
  private userPresence: Map<string, 'online' | 'offline' | 'away'> = new Map();

  // constructor(private readonly userRepository: UserRepository) {} // ユーザーリポジトリをインジェクト

  async updateUserPresence(userId: string, status: 'online' | 'offline' | 'away') {
    const currentStatus = this.userPresence.get(userId);
    if (currentStatus === status) {
      return; // 状態に変更がなければ何もしない
    }

    this.userPresence.set(userId, status);
    this.logger.log(`User ${userId} presence updated to: ${status}`);

    // DBにプレゼンス状態を永続化する場合 (例: last_seen_at更新など)
    // await this.userRepository.updateUserPresence(userId, status);

    // 他のサービスへの通知 (例: Kafka, RabbitMQなど)
    // this.eventBus.publish(new UserPresenceUpdatedEvent(userId, status));
  }

  getUserPresence(userId: string): 'online' | 'offline' | 'away' {
    return this.userPresence.get(userId) || 'offline';
  }
}

なお、JwtWsAuthGuard が JwtService を注入できるように、モジュールへの登録が必要です。secret は環境変数から読み込みます。

// src/realtime/realtime.module.ts
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AppWebSocketGateway } from './websocket.gateway';
import { ConnectionManager } from './connection.manager';
import { RealtimeService } from './realtime.service';
import { JwtWsAuthGuard } from '../auth/jwt-ws.guard';

@Module({
  imports: [
    JwtModule.register({
      secret: process.env.JWT_SECRET,
      signOptions: { expiresIn: '1h' },
    }),
  ],
  providers: [AppWebSocketGateway, ConnectionManager, RealtimeService, JwtWsAuthGuard],
})
export class RealtimeModule {}

クライアント側の実装

1. PresenceClient:堅牢なWebSocket接続の核

// src/realtime/presence.client.ts
import { io, Socket } from 'socket.io-client';
import { ReconnectStrategy } from './reconnect.strategy';

type PresenceStatus = 'online' | 'away' | 'offline';
type Message = { event: string; payload: any };

export class PresenceClient {
  private socket: Socket | null = null;
  private token: string;
  private userId: string;
  private endpoint: string;
  private reconnectStrategy: ReconnectStrategy;
  private messageBuffer: Message[] = [];
  private eventListeners: Map<string, Set<(payload: any) => void>> = new Map();
  private manualDisconnect = false;

  constructor(endpoint: string, token: string, userId: string) {
    this.endpoint = endpoint;
    this.token = token;
    this.userId = userId;
    this.reconnectStrategy = new ReconnectStrategy();
  }

  // トークンを差し替える。再接続時は新しいトークンで認証される
  // (REST APIでのリフレッシュを想定。呼び出しは利用側で行う)
  setToken(token: string): void {
    this.token = token;
  }

  connect(): void {
    if (this.socket?.connected) {
      console.warn('WebSocket is already connected.');
      return;
    }

    this.manualDisconnect = false;
    // サーバーは NestJS + Socket.IO のため、ブラウザ標準の WebSocket ではなく
    // socket.io-client で接続する(Engine.IO のハンドシェイクが必要で、
    // 標準 WebSocket では接続が確立できない)。
    // auth に JWT を載せると、サーバー側の JwtWsAuthGuard が
    // client.handshake.auth.token として読み取る
    this.socket = io(this.endpoint, {
      auth: { token: this.token },
      reconnection: false, // 再接続は ReconnectStrategy に任せる
      transports: ['websocket'],
    });

    this.socket.on('connect', () => this.onOpen());
    this.socket.on('disconnect', (reason) => this.onClose(reason));
    this.socket.on('connect_error', (error) => this.onConnectError(error));
    // 登録済みのイベントリスナーを新しいソケットへ付け直す
    this.eventListeners.forEach((listeners, eventName) => {
      listeners.forEach((listener) => this.socket!.on(eventName, listener));
    });
  }

  private onOpen(): void {
    console.log('WebSocket connected.');
    this.reconnectStrategy.reset(); // 接続成功で再接続戦略をリセット
    this.flushMessageBuffer(); // バッファされたメッセージを送信
    // Socket.IO のエンジンレベルハートビート (pingInterval / pingTimeout) が
    // 死活監視とアイドルタイムアウト回避を担うため、アプリ独自の ping/pong は不要
    // オンライン化はサーバー側の handleConnection が行い、全員へ通知されるため、
    // ここで 'online' を送る必要はない(送ると同じ通知が重複する)
    this.emit('connected', { userId: this.userId }); // UIなどに接続イベントを通知
  }

  private onClose(reason: string): void {
    this.emit('disconnected', { userId: this.userId, reason });
    // 切断時のオフライン化はサーバー側の handleDisconnect が行うため、
    // ここで 'offline' を送る必要はない(送ると再接続時に古い 'offline' が
    // バッファ経由で届き、一時的に誤ったプレゼンスが表示される)
    if (this.manualDisconnect) {
      return; // 明示的な切断では再接続しない
    }
    if (reason === 'io server disconnect') {
      // サーバーが切断した(handleConnection での認証失敗など)。
      // 同じトークンで再接続しても通らないため再接続しない
      console.error('Disconnected by server (authentication failed?). Not attempting to reconnect.');
      this.emit('auth_error', { userId: this.userId });
      return;
    }
    console.warn(`WebSocket closed: ${reason}. Will attempt to reconnect.`);
    this.reconnectStrategy.reconnect(() => this.connect());
  }

  private onConnectError(error: Error): void {
    console.error('WebSocket connection error:', error.message);
    // 接続確立前の失敗では 'disconnect' は発火しないため、ここで再接続を進める
    if (this.manualDisconnect) return;
    this.emit('disconnected', { userId: this.userId, reason: 'connect_error' });
    this.reconnectStrategy.reconnect(() => this.connect());
  }

  send(event: string, payload: any): void {
    const message = { event, payload };
    if (this.socket?.connected) {
      this.socket.emit(event, payload);
    } else {
      console.warn('WebSocket not connected. Buffering message:', message);
      this.messageBuffer.push(message);
    }
  }

  private flushMessageBuffer(): void {
    while (this.messageBuffer.length > 0 && this.socket?.connected) {
      const message = this.messageBuffer.shift();
      if (message) {
        this.socket.emit(message.event, message.payload);
      }
    }
  }

  sendPresenceUpdate(status: PresenceStatus): void {
    this.send('update_presence', { status });
  }

  on(eventName: string, listener: (payload: any) => void): () => void {
    if (!this.eventListeners.has(eventName)) {
      this.eventListeners.set(eventName, new Set());
    }
    this.eventListeners.get(eventName)!.add(listener);
    if (this.socket) {
      this.socket.on(eventName, listener);
    }

    // unsubscribe関数を返す
    return () => {
      this.eventListeners.get(eventName)?.delete(listener);
      this.socket?.off(eventName, listener);
      if (this.eventListeners.get(eventName)?.size === 0) {
        this.eventListeners.delete(eventName);
      }
    };
  }

  private emit(eventName: string, payload: any): void {
    this.eventListeners.get(eventName)?.forEach(listener => listener(payload));
  }

  disconnect(): void {
    this.manualDisconnect = true;
    this.reconnectStrategy.reset(); // 完全切断なので再接続戦略をリセット
    if (this.socket) {
      // 'disconnect' イベント経由で onClose が 'disconnected' を通知する
      this.socket.disconnect(); // サーバー側でオフライン化される
      this.socket = null;
    } else {
      this.emit('disconnected', { userId: this.userId, reason: 'Client initiated' });
    }
    console.log('WebSocket fully disconnected.');
  }

  get clientStatus(): 'connected' | 'disconnected' | 'connecting' | 'reconnecting' {
    if (this.socket?.connected) return 'connected';
    if (this.reconnectStrategy.isReconnecting()) return 'reconnecting';
    if (this.socket) return 'connecting';
    return 'disconnected';
  }
}

2. ReconnectStrategy:自動再接続ロジック

// src/realtime/reconnect.strategy.ts
export class ReconnectStrategy {
  private reconnectAttempts = 0;
  private isReconnectingFlag = false;
  private readonly MAX_RECONNECT_ATTEMPTS = 10; // 最大再接続試行回数
  private readonly BASE_RECONNECT_DELAY_MS = 1000; // 1秒

  reconnect(callback: () => void): void {
    if (this.reconnectAttempts >= this.MAX_RECONNECT_ATTEMPTS) {
      console.error(`Max reconnect attempts (${this.MAX_RECONNECT_ATTEMPTS}) reached. Stopping reconnection.`);
      this.isReconnectingFlag = false;
      return;
    }

    this.isReconnectingFlag = true;
    this.reconnectAttempts++;
    // 指数バックオフ: 1s, 2s, 4s, 8s, ...
    const delay = Math.min(
      this.BASE_RECONNECT_DELAY_MS * Math.pow(2, this.reconnectAttempts - 1),
      30000 // 最大30秒の遅延
    );

    console.log(`Attempting to reconnect in ${delay / 1000} seconds (Attempt: ${this.reconnectAttempts})...`);
    setTimeout(() => {
      callback();
    }, delay);
  }

  reset(): void {
    this.reconnectAttempts = 0;
    this.isReconnectingFlag = false;
    console.log('Reconnect strategy reset.');
  }

  isReconnecting(): boolean {
    return this.isReconnectingFlag;
  }
}

3. Reactコンポーネントでの利用例

// src/components/PresenceIndicator.tsx
import React, { useEffect, useState, useRef } from 'react';
import { PresenceClient } from '../realtime/presence.client';

interface PresenceIndicatorProps {
  userId: string;
  jwtToken: string;
  wsEndpoint: string;
}

const PresenceIndicator: React.FC<PresenceIndicatorProps> = ({ userId, jwtToken, wsEndpoint }) => {
  const [status, setStatus] = useState<'online' | 'offline' | 'away'>('offline');
  const [connectionStatus, setConnectionStatus] = useState<string>('disconnected');
  const presenceClientRef = useRef<PresenceClient | null>(null);

  useEffect(() => {
    // クライアントサイドでのみPresenceClientを初期化
    if (typeof window === 'undefined' || !userId || !jwtToken || !wsEndpoint) return;

    const client = new PresenceClient(wsEndpoint, jwtToken, userId);
    presenceClientRef.current = client;

    // イベントリスナーの登録
    const unsubscribePresence = client.on('presence_update', (data: { userId: string; status: 'online' | 'away' | 'offline' }) => {
      if (data.userId === userId) {
        setStatus(data.status);
      }
    });
    const unsubscribeConnected = client.on('connected', () => setConnectionStatus('connected'));
    const unsubscribeDisconnected = client.on('disconnected', () => setConnectionStatus(client.clientStatus)); // reconnectingかも
    const unsubscribeAuthError = client.on('auth_error', () => {
      setConnectionStatus('authentication_failed');
      console.error('WebSocket authentication failed. Please re-login.');
      // ユーザーをログアウトさせるなどの処理
    });

    client.connect();

    // ユーザーがブラウザタブを閉じる/ページを離れる際に 'away' または 'offline' を通知
    const handleVisibilityChange = () => {
      if (document.visibilityState === 'hidden') {
        client.sendPresenceUpdate('away'); // タブが非アクティブになったら離席
      } else {
        client.sendPresenceUpdate('online'); // タブがアクティブになったらオンライン
      }
    };
    document.addEventListener('visibilitychange', handleVisibilityChange);

    const handleBeforeUnload = () => {
      // 切断時のオフライン化はサーバー側の handleDisconnect が行うため、
      // ここで 'offline' を送る必要はない
      client.disconnect(); // 確実に切断処理を行う
    };
    window.addEventListener('beforeunload', handleBeforeUnload);

    // クリーンアップ関数
    return () => {
      unsubscribePresence();
      unsubscribeConnected();
      unsubscribeDisconnected();
      unsubscribeAuthError();
      document.removeEventListener('visibilitychange', handleVisibilityChange);
      window.removeEventListener('beforeunload', handleBeforeUnload);
      client.disconnect(); // コンポーネトアンマウント時にWebSocketを切断
    };
  }, [userId, jwtToken, wsEndpoint]); // 依存配列に含める

  const handleManualStatusChange = (newStatus: 'online' | 'away' | 'offline') => {
    if (presenceClientRef.current) {
      presenceClientRef.current.sendPresenceUpdate(newStatus);
    }
  };

  return (
    <div>
      <p>Your Status: <span style={{ color: status === 'online' ? 'green' : (status === 'away' ? 'orange' : 'red') }}>{status}</span></p>
      <p>Connection Status: {connectionStatus}</p>
      <div>
        <button onClick={() => handleManualStatusChange('online')} disabled={status === 'online'}>Online</button>
        <button onClick={() => handleManualStatusChange('away')} disabled={status === 'away'}>Away</button>
        <button onClick={() => handleManualStatusChange('offline')} disabled={status === 'offline'}>Offline</button>
      </div>
    </div>
  );
};

export default PresenceIndicator;

注意点・ハマりどころ

WebアプリケーションにおけるWebSocketの実装は、一見するとシンプルなAPIに思えますが、本番環境で堅牢かつ安定したリアルタイム通信を維持するには、数多くの落とし穴が存在します。特にマイクロサービスアーキテクチャや分散環境においては、設計段階でこれらの潜在的な問題を織り込んでおく必要があります。

プロキシ・ロードバランサーのタイムアウトとハートビート

最も頻繁に遭遇する問題の一つが、クライアントとサーバー間の経路に存在するプロキシやロードバランサーが設定するアイドルタイムアウトです。WebSocket接続はTCP接続の上に確立されますが、アプリケーションレベルでのデータ送受信が一定時間ないと、これらのミドルウェアは接続を「アイドル」と判断し、強制的に切断してしまうことがあります。これはユーザーがチャットをしばらく操作しない、あるいはプレゼンス情報が変化しないといったシナリオで顕在化し、結果的にクライアントのPresenceClientが意図しない切断を経験します。

この問題の対策は、Socket.IOのエンジンレベルハートビートです。WebSocketGateway のオプションで設定した pingInterval: 10000 / pingTimeout: 5000 により、サーバーから10秒ごとにpingが送られ、クライアントからのpongが5秒以内にない場合は切断と判断されます。10秒という間隔はALBの60秒アイドルタイムアウトを下回るため、アイドル状態でも接続が維持されます。アプリ独自のping/pongメッセージを別途実装する必要はありません。むしろ独自実装は、サーバーが応答しないイベント名との齟齬があると、ハートビートが「切断防止」ではなく「切断の原因」になるため避けるべきです。

JWT認証のライフサイクルと再認証戦略

WebSocket接続時の認証にはJWTが広く利用されますが、JWTには有効期限があります。長期的なWebSocket接続の場合、セッション中にJWTが期限切れとなる状況が当然発生します。ここで考慮すべきは、期限切れのJWTを持つクライアントからのメッセージを JwtWsAuthGuard が拒否するだけでなく、その後の挙動です。

期限切れの扱いは、検知されるタイミングで異なります。接続確立時に期限切れトークンが使われた場合は handleConnection の検証で切断されます。一方、接続中にトークンが期限切れとなった場合、ガードは各メッセージを拒否しますが、接続自体は維持されます。そのためクライアント側(PresenceClient)は、再接続の前に setToken() で新しいJWTへ差し替えてから接続し直す必要があります。重要なのは、トークンが期限切れになったにも関わらず、古いトークンで通信を継続させない厳格なセキュリティポリシーと、ユーザー体験を損なわないスムーズな再認証フローの両立です。新しいJWTの取得には、通常のREST API経由でのリフレッシュトークン利用などが考えられます。

スケーラビリティとSticky Sessionの回避

WebSocket Gatewayを複数インスタンスで運用する場合、ロードバランサーで特定のクライアントからの接続を常に同じサーバーインスタンスにルーティングする「Sticky Session」を利用することは、スケーラビリティと可用性の観点から推奨されません。特定のインスタンスに障害が発生した場合にそのインスタンスに接続していた全クライアントに影響が及び、またロードバランシングの効率も低下します。

モダンなWebSocketGatewayは、各サーバーインスタンスが互いに疎結合に動作し、クライアントの接続状態(PresenceClientからの接続)を共通のストア(例: Redis Pub/Sub、Shared Database)で管理するべきです。RealtimeService内のConnectionManagerは、どのクライアントがどのサーバーインスタンスに接続しているかを意識せず、メッセージを適切な配信メカニズムに乗せてブロードキャストや特定クライアントへの送信を実現できる設計が求められます。これにより、水平スケーリングが容易になり、特定のサーバー障害時の影響範囲も限定されます。

運用と監視の重要性

リアルタイム通信環境は、従来のHTTPベースのサービスよりもデバッグや障害検知が困難な場合があります。WebSocketGateway、RealtimeService、ConnectionManagerといった各コンポーネントにおける、接続数、切断イベント、メッセージ処理レイテンシ、エラーレートなどのメトリクスを詳細に収集し、監視することは極めて重要です。予期せぬ切断数の増加やメッセージ配信遅延は、システム全体のボトルネックや潜在的な障害の兆候を示します。適切なアラート設定と迅速な障害対応体制が、信頼性の高いサービス提供には不可欠です。

まとめ

チャットメッセージ不達というユーザー報告から始まった今回のケーススタディは、Webアプリケーションにおけるリアルタイム通信の信頼性がいかに重要かを示しています。頻繁なWebSocket切断と再接続失敗という課題は、単なる実装のミスではなく、ネットワークインフラ、マイクロサービスアーキテクチャ、そしてセキュリティの各層にまたがる複合的な問題でした。

この課題を克服するため、私たちはフロントエンドとバックエンド双方で堅牢な設計思想を再構築しました。クライアント側ではReconnectStrategyとPresenceClientによる自動再接続、Socket.IOのハートビート、メッセージバッファリングを実装し、断続的なネットワーク環境でもユーザー体験を損なわない設計を重視しました。サーバー側では、WebSocketGateway、RealtimeService、ConnectionManagerを用いて接続を疎結合に保ちつつ、JwtWsAuthGuardによるセキュアな認証認可を徹底。インフラ・ネットワークレイヤーでの高可用性確保と運用コスト最適化のバランスも考慮に入れ、堅牢なリアルタイム通信基盤を構築しました。

リアルタイム通信の実装は、表面的なAPI利用にとどまらず、多角的な視点での設計が不可欠です。本記事で示した実践的なアプローチが、皆さんのプロダクトにおける「切れない・遅れない」リアルタイム通信を実現し、ユーザー体験を向上させる一助となれば幸いです。まずは、自社のリアルタイム通信要件を再評価し、今回紹介した堅牢な設計パターンを段階的に導入することを検討してください。


エンジニアのスキルシェアプラットフォーム「DokuPro」

教えたい人と学びたい人を繋ぐDokuProでは、新規登録(先生・生徒)を募集中です。
詳細はこちら: https://dokupro.dev/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?