Skip to content

Bug: Gemini SSE streaming response not cleaned up on client disconnect, leaks server resources #261

Description

@anshul23102

Bug Report: Abandoned SSE Streams Keep Gemini API Call Running After Client Disconnects

Description

The ApexAIPage uses Server-Sent Events (SSE) to stream Gemini AI responses.
When the user navigates away or closes the page mid-stream, the browser
closes the SSE connection, but the Express server continues calling
stream.next() on the Gemini generateContentStream until the response
completes. On a busy server, many abandoned streams accumulate as live Gemini
API calls, consuming tokens and server memory unnecessarily.

Steps to Reproduce

  1. Navigate to the AI Roadmap page and start generating a roadmap.
  2. Immediately navigate away before the response finishes.
  3. Monitor the Express server: Gemini API streaming calls continue for
    the duration of the expected response (30-60 seconds).
  4. Repeat 10 times: observe 10 live Gemini calls consuming tokens concurrently.

Root Cause

The SSE route handler does not listen for the req.on('close', ...) event
to abort the Gemini streaming call when the client disconnects.

Impact

Abandoned streams consume Gemini API quota and server memory proportional to
the number of concurrent navigations-away. In production this can exhaust
the Gemini API rate limit for legitimate users.

Proposed Fix

Listen for client disconnect and abort the Gemini stream:

router.get("/api/ai/stream", async (req, res) => {
  res.setHeader("Content-Type", "text/event-stream");
  const controller = new AbortController();
  req.on("close", () => controller.abort());

  try {
    const stream = await model.generateContentStream(prompt, { signal: controller.signal });
    for await (const chunk of stream) {
      if (controller.signal.aborted) break;
      res.write(`data: ${JSON.stringify({ text: chunk.text() })}

`);
    }
  } catch (err) {
    if (err.name !== "AbortError") throw err;
  } finally {
    res.end();
  }
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions