Skip to content
spot_the_ai_bug

Resource leaks: interview questions

A resource leak acquires something finite (a file descriptor, connection, listener or timer) and fails to release it on some path, until the process runs out.

How to spot it in code review

  • Pair every open/add/subscribe with its close/remove/unsubscribe.
  • Check that cleanup runs on early returns and errors too.
  • Prefer defer, try-with-resources, with and cleanup functions.
  • Ask what happens when this runs 10,000 times.

Why AI-generated code gets this wrong

Cleanup is invisible in short examples, and models often add early returns without re-checking that cleanup still runs.

Resource leaks: 3 practice questions

Q1JavaScriptmedium

Scroll listener per page view

trackScrollDepth() runs on every client-side route change in a single-page app. What goes wrong after a few minutes of browsing?

export function trackScrollDepth(pageId) {  let maxDepth = 0;  window.addEventListener("scroll", () => {    const depth = (window.scrollY + window.innerHeight) / document.body.scrollHeight;    maxDepth = Math.max(maxDepth, depth);  });  return () => sendBeacon("/analytics", { pageId, maxDepth });}
Show answer

line 3 · Resource leak

A new scroll listener is added on every navigation and never removed. Old listeners keep running (and keep their closures alive), so each scroll does more and more work and memory grows for the whole session.

Fix
  const onScroll = () => {    const depth = (window.scrollY + window.innerHeight) / document.body.scrollHeight;    maxDepth = Math.max(maxDepth, depth);  };  window.addEventListener("scroll", onScroll, { passive: true });  return () => {    window.removeEventListener("scroll", onScroll);    sendBeacon("/analytics", { pageId, maxDepth });  };

Interview follow-up: Removing a listener requires the same function reference that was added, so name the handler.

Q2Gomedium

Unclosed HTTP response body

FetchStatus() is called every few seconds by a health checker. After a day the service runs out of file descriptors. Why?

func FetchStatus(client *http.Client, url string) (int, error) {	resp, err := client.Get(url)	if err != nil {		return 0, err	}	return resp.StatusCode, nil}
Show answer

line 2 · Resource leak

The response body is never closed. Each call leaves a connection and its file descriptor open, and they can't be returned to the pool, so the process eventually hits its open-file limit.

Fix
	resp, err := client.Get(url)	if err != nil {		return 0, err	}	defer resp.Body.Close()

Interview follow-up: Some interviewers also ask about draining the body (io.Copy(io.Discard, resp.Body)) so keep-alive connections can be reused.

Q3Javamedium

JDBC connection never closed

emailExists() is called on every signup. After some traffic, all requests hang waiting for a database connection. Why?

public boolean emailExists(String email) throws SQLException {    Connection conn = dataSource.getConnection();    PreparedStatement ps = conn.prepareStatement("SELECT 1 FROM users WHERE email = ?");    ps.setString(1, email);    ResultSet rs = ps.executeQuery();    return rs.next();}
Show answer

line 2 · Resource leak

The connection, statement and result set are never closed, so every call keeps a pooled connection checked out. Once the pool is exhausted, new requests block until they time out.

Fix
    try (Connection conn = dataSource.getConnection();         PreparedStatement ps = conn.prepareStatement("SELECT 1 FROM users WHERE email = ?")) {        ps.setString(1, email);        try (ResultSet rs = ps.executeQuery()) {            return rs.next();        }    }

Interview follow-up: Explain why try-with-resources beats a finally block: it closes in reverse order and keeps suppressed exceptions.

Every day, everyone gets the same pull request written by AI. It looks clean. It has comments. It has exactly one real bug.

  1. 1

    Find the line

    Tap the buggy line, then hit Submit. You get 3 attempts.

  2. 2

    Read the hints

    A miss within 2 lines is 🔥 Warm. Anything further is ❄️ Cold.

  3. 3

    Name the bug

    Found it? Bonus round: pick the bug type from 4 options. It doesn't affect your win, just your bragging rights.

// your share card

found in 3/3

🟥 cold miss · 🟨 warm miss · 🟩 found · ⬛ unused

Keyboard: ↑ ↓ to move between lines, Enter to submit. A new bug drops every day at midnight IST.

0
Played
0
Win %
0
Streak
0
Max

Attempts distribution