porsager / porsager/postgres

Memory leak in subscribe

Open
#1,087 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
8.7k
Forks
374
Avg merge
11d 16h
Merged PRs (30d)
1

Description

Hello!

I'm heavily using subscribe on a project I'm currently working on and I think there is a small memory leak in the cleanup logic of the subscribe function. This is the main subscribe function. Most of the cleanup is done fully but that additional listener stream && stream.on('error', onerror) at the bottom is never removed. After a while, this does have an impact.

async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {
  event = parseEvent(event)

  if (!connection)
    connection = init(sql, slot, options.publications)

  const subscriber = { fn, onsubscribe }
  const fns = subscribers.has(event)
    ? subscribers.get(event).add(subscriber)
    : subscribers.set(event, new Set([subscriber])).get(event)

  const unsubscribe = () => {
    fns.delete(subscriber)
    fns.size === 0 && subscribers.delete(event)
+   stream && stream.removeListener('error', onerror)
  }

  return connection.then(x => {
    connected(x)
    onsubscribe()
    stream && stream.on('error', onerror)
    return { unsubscribe, state, sql }
  })
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue points to the main subscribe function and shows where the stream error listener is attached; start there and trace how stream and onerror are handled during connection.then. Done means unsubscribe no longer leaves that listener attached, while the existing subscription behavior remains intact.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, node.js, postgresql
Domain
databases
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.