Skip to content

WebSocket Connection Memory Leak in RealtimeClient #1840

@tanmaysharma2001

Description

@tanmaysharma2001

Description

There is a memory leak in RealtimeClient._teardownConnection() where WebSocket connections were not properly closed before being nullified, causing connections to remain open in memory indefinitely. I have fixed that.

The original implementation in packages/core/realtime-js/src/RealtimeClient.ts:596-606 would set WebSocket event handlers to null and nullify the connection reference without first ensuring the WebSocket was properly closed:

private _teardownConnection(): void {
  if (this.conn) {
    this.conn.onopen = null
    this.conn.onerror = null
    this.conn.onmessage = null
    this.conn.onclose = null
    this.conn = null  // reference nullified without ensuring closure
  }
}

I intend to submit a PR for this issue.

Suggested solution

Enhanced _teardownConnection() to explicitly close WebSocket connections before cleanup:

private _teardownConnection(): void {
  if (this.conn) {
    // Ensure connection is properly closed first
    if (
      this.conn.readyState === SOCKET_STATES.open ||
      this.conn.readyState === SOCKET_STATES.connecting
    ) {
      try {
        this.conn.close()
      } catch (e) {
        this.log('error', 'Error closing connection', e)
      }
    }

    this.conn.onopen = null
    this.conn.onerror = null
    this.conn.onmessage = null
    this.conn.onclose = null
    this.conn = null
  }
  this._clearAllTimers()
  this.channels.forEach((channel) => channel.teardown())
}

Alternative

No response

Additional context

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions