Universpace
Universpace

Reputation: 47

Socket.IO to().emit() works locally but not on EC2 behind an ALB (WSS configured)

I’m using NestJS with Socket.IO and RabbitMQ. Locally, everything works as expected: when the client emits a send_message event, the server processes it and then sends a receive_message event to the correct room, which the client receives. However, once I deploy this to an AWS EC2 instance behind an Application Load Balancer (ALB) with WSS configured, the client never receives the receive_message event.

Below is a simplified version of my code.

// socketio.gateway.ts
@WebSocketGateway({
  namespace: "",
  cors: { origin: "*" },
  transports: ["websocket"]
})
export class SocketIoGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  // ... other methods ...
}
// my-socket-service.service.ts
@Injectable()
export class MySocketService implements OnModuleInit {
  constructor(
    private readonly eventsGateway: SocketIoGateway,
    private readonly amqpConnection: AmqpConnection,
    // ...
  ) {}

  async onModuleInit() {
    // Register Socket.IO event
    this.eventsGateway.registerEvent("send_message", this.handleSendMessage.bind(this));
  }

  private async handleSendMessage(client: Socket, data: FileMessageInput) {
    // Process incoming data and publish via RabbitMQ
    await this.publishMessage(plainToInstance(DataDTO, data));
  }

  async publishMessage(dataDTO: DataDTO) {
    try {
      await this.amqpConnection.publish("queue", "message.new", dataDTO);
    } catch (error) {
      // ...
      throw error;
    }
  }

  @RabbitSubscribe({
    exchange: "queue",
    routingKey: "message.new",
    queue: "my_queue",
  })
  async handleMessage(data: DataDTO, amqpMsg: ConsumeMessage) {
    // Once the message is processed, emit to the correct room
    try {
      const resData = await this.processMessage(data);
      await this.eventsGateway.server
        .to(`room-${resData.roomId}`)
        .emit("receive_message", resData); // <-- This works locally, but not on EC2
      // ...
    } catch (error) {
      // ...
    }
  }
}

What I’ve tried:

  1. Local environment (Mac/Windows) → Works perfectly. Client emits send_message, server eventually sends receive_message.
  2. Production environment (Amazon Linux EC2)
    • Deployed behind an ALB with WSS configured.
    • I’ve confirmed that the connection is upgrading to WebSocket successfully.
  3. RedisAdapter: I’ve already configured a Redis adapter for Socket.IO to handle scalability. No issues or errors are logged, but the receive_message events simply do not arrive at the client.

Symptoms and Debugging:

Question:

Any guidance or suggestions would be greatly appreciated. Thanks in advance!

Upvotes: 0

Views: 23

Answers (0)

Related Questions