Skip to content

Cursor not closed: resource leak

Quick summary

You opened a cursor but did not close it — the database keeps the cursor and its resources allocated until the session ends.

Why this happens

  • A cursor was opened for iterating results but was never explicitly closed after the loop

  • An exception occurred before the cursor close statement, leaving the cursor open

  • The cursor was opened in a function that returned early without closing the cursor

Minimal example

✗ Broken code
async function getItems() {
  const cursor = db.collection('items').find({});
  while (await cursor.hasNext()) {
    const item = await cursor.next();
    if (item.invalid) return []; // early return, cursor not closed!
  }
}
✓ Fixed code
async function getItems() {
  const cursor = db.collection('items').find({});
  try {
    const items = [];
    while (await cursor.hasNext()) {
      const item = await cursor.next();
      if (item.invalid) return [];
      items.push(item);
    }
    return items;
  } finally {
    await cursor.close(); // always closed
  }
}

Using try/finally ensures the cursor is closed even on early return or exception, preventing the resource leak.

How to diagnose

  • Check for open cursors in the database session monitoring view or system catalog

  • Review code that opens cursors and verify each has a corresponding close in all code paths

  • Monitor connection pool usage for steady growth indicating cursor or connection leaks

How to fix

  • Use a try/finally block to ensure the cursor is closed even if an exception occurs

  • Use a context manager or resource-with pattern that automatically closes the cursor

  • Set a cursor timeout on the database to auto-close idle cursors after a period

How to prevent

  • Always use try/finally or context managers to guarantee cursor cleanup in all code paths

  • Monitor open cursor counts and set limits to detect leaks before they exhaust resources

Related Resources

Related Glossary

Related Lessons

← Back to language