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
- Navigate to the AI Roadmap page and start generating a roadmap.
- Immediately navigate away before the response finishes.
- Monitor the Express server: Gemini API streaming calls continue for
the duration of the expected response (30-60 seconds).
- 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();
}
});
Bug Report: Abandoned SSE Streams Keep Gemini API Call Running After Client Disconnects
Description
The
ApexAIPageuses 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 GeminigenerateContentStreamuntil the responsecompletes. On a busy server, many abandoned streams accumulate as live Gemini
API calls, consuming tokens and server memory unnecessarily.
Steps to Reproduce
the duration of the expected response (30-60 seconds).
Root Cause
The SSE route handler does not listen for the
req.on('close', ...)eventto 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: