Skip to article
API429 / Field notes

Gemini Streaming Responses: SSE Framing, Partial Output Rules, and 429 Controls

Handle Server-Sent Events (SSE) for Gemini and OpenAI-compatible streaming responses with pre-stream vs mid-stream failure classification and [DONE] verification.

Hourglass and a queue of paper request cards
Editorial photo illustration: Hourglass and a queue of paper request cards. Topic: Gemini Streaming Responses: SSE Framing, Partial Output Rules, and 429 Controls.

Enabling streaming on Gemini (models.streamGenerateContent?alt=sse) or OpenAI-compatible chat completions (POST /v1/chat/completions with "stream": true) improves time-to-first-token (TTFT) for interactive users, but fundamentally changes error handling. Once an HTTP 200 OK header and the first data: chunk flush to the caller, an upstream rate-limit event, socket drop, or token cutoff can no longer be communicated as a clean HTTP status code—and blindly retrying after visible tokens have already rendered duplicates text and doubles token spend.

This guide defines the client-side state machine for Gemini and OpenAI-compatible Server-Sent Events (SSE) streaming: separating pre-stream HTTP errors from mid-stream disconnects, verifying terminal finish_reason / finishReason and data: [DONE] markers, holding concurrency leases until stream close, and coordinating with application retry budgets and scoped workload health checks.

Separate five streaming lifecycle states before retrying

As documented in the API429 streaming documentation, Google Gemini generateContent reference, and the WHATWG Server-Sent Events specification, an SSE stream is only complete when the client observes a valid terminal finish reason and the stream terminator.

Streaming phase / outcome Observed HTTP & SSE state Has visible output reached the user? Safe application recovery action
Pre-stream rejection (HTTP 429 / 503) Non-200 status before any SSE data: frame is emitted No (chunks_emitted == 0) Eligible for bounded retry budget after honoring Retry-After
Empty stream / keepalive-only drop HTTP 200, text/event-stream, but socket closes with zero content deltas No (content_chars == 0) Reconcile deadline; safe for one bounded retry if no side effect occurred
Mid-stream disconnect after partial output HTTP 200, one or more content deltas rendered, then socket closes without [DONE] Yes (content_chars > 0) Do not auto-retry full prompt inline; mark partial output interrupted and offer explicit user resume/regenerate
Truncated finish (MAX_TOKENS / length, SAFETY) Stream closes cleanly with non-STOP terminal reason Yes Do not retry identical request; handle policy stop or increase max_tokens on next turn
Complete verified stream Non-empty content deltas + terminal finish_reason="stop" (STOP) + data: [DONE] Yes Release concurrency slot and commit complete output to conversation store

Four production guardrails for SSE streaming clients

Whether building a custom web UI or configuring streaming clients like Cursor, Claude Code, or Open WebUI, enforce these four rules:

  1. Hold local concurrency semaphores until stream teardown: A worker slot is busy from request dispatch until the final data: [DONE] frame or socket finally block runs. Releasing your semaphore as soon as HTTP 200 headers arrive lets hundreds of concurrent streams pile up and trigger HTTP 429 on the next turn. See Gemini API rate limits and queue design.
  2. Enforce two separate timeouts (TTFT vs inter-chunk idle): Use a tight time-to-first-token timeout (for example, 10–15 seconds) before the first delta arrives, and a per-chunk idle timeout (for example, 15–20 seconds between SSE frames) so stalled connections do not hang worker pools indefinitely.
  3. Buffer and validate before mutating downstream stores: Never pipe unverified partial SSE tokens directly into a database write or webhook action. For JSON extraction, follow structured-output pipeline validation after the full payload is assembled.
  4. Propagate client cancellation (AbortController) upstream: When a user closes the browser tab or clicks "Stop generating", abort the upstream HTTP stream immediately so you stop consuming output tokens and free your concurrency lease.

Handling tool calls, citations, and usage metadata in SSE streams

Modern Gemini and OpenAI-compatible streams deliver more than plain text deltas. Production SSE parsers must account for three additional frame patterns without corrupting state:

  • Fragmented tool-call argument chunks: Function calling over SSE streams arrives as incremental JSON string fragments across multiple frames. Accumulate fragments per tool call index in a dedicated buffer and only parse or execute the tool after observing `finish_reason == "tool_calls"` and `data: [DONE]`.
  • Keepalive comments and empty deltas: Gateways and reverse proxies frequently emit leading SSE comment lines (starting with a colon, such as `": keepalive"`) or role-initialization chunks with empty content strings. Ignore comment lines and reset your inter-chunk idle timer only when valid protocol frames arrive.
  • Final usage-chunk accounting: When requesting stream usage statistics, the final data frame before `[DONE]` often contains token usage counters with an empty `choices` array or null delta. Reconcile that usage object with your token counting and cost budget ledger so streamed calls are tracked with the same precision as non-streaming requests.

Runnable offline Python SSE stream framing and retry-safety evaluator

The following self-contained Python 3.10+ module parses raw OpenAI-compatible SSE lines, classifies pre-stream vs mid-stream failures, and determines whether an automatic retry is safe without duplicating visible output:

from __future__ import annotations
from dataclasses import dataclass
import json
from typing import Sequence


@dataclass(frozen=True)
class StreamEvaluation:
    state: str                 # "complete", "pre_stream_http_error", "empty_stream_drop", "partial_stream_interrupted", "incomplete_finish"
    safe_for_auto_retry: bool
    assembled_text: str
    finish_reason: str | None
    saw_done_marker: bool
    diagnostic: str


def evaluate_sse_session(
    *,
    http_status: int,
    raw_lines: Sequence[str],
) -> StreamEvaluation:
    if http_status != 200:
        retryable = http_status in (429, 502, 503, 504)
        return StreamEvaluation(
            state="pre_stream_http_error",
            safe_for_auto_retry=retryable,
            assembled_text="",
            finish_reason=None,
            saw_done_marker=False,
            diagnostic=f"http_{http_status}_before_stream_start",
        )

    deltas: list[str] = []
    finish_reason: str | None = None
    saw_done = False

    for raw in raw_lines:
        line = raw.strip()
        if not line or line.startswith(":"):
            continue
        if not line.startswith("data:"):
            continue
        payload = line[5:].strip()
        if payload == "[DONE]":
            saw_done = True
            break
        try:
            event = json.loads(payload)
        except json.JSONDecodeError:
            return StreamEvaluation(
                state="partial_stream_interrupted" if deltas else "empty_stream_drop",
                safe_for_auto_retry=len(deltas) == 0,
                assembled_text="".join(deltas),
                finish_reason=finish_reason,
                saw_done_marker=False,
                diagnostic="malformed_sse_json_frame",
            )
        for choice in event.get("choices", []):
            piece = (choice.get("delta") or {}).get("content")
            if isinstance(piece, str) and piece:
                deltas.append(piece)
            if choice.get("finish_reason"):
                finish_reason = str(choice["finish_reason"])

    text = "".join(deltas)
    if not text and not saw_done:
        return StreamEvaluation("empty_stream_drop", True, "", finish_reason, False, "zero_content_before_disconnect")
    if not saw_done or finish_reason is None:
        return StreamEvaluation("partial_stream_interrupted", False, text, finish_reason, saw_done, "missing_done_or_finish_reason")
    if finish_reason not in ("stop", "STOP"):
        return StreamEvaluation("incomplete_finish", False, text, finish_reason, True, f"non_stop_finish_{finish_reason}")
    return StreamEvaluation("complete", False, text, finish_reason, True, "verified_sse_completion")


if __name__ == "__main__":
    healthy_sse = [
        'data: {"choices":[{"delta":{"content":"Hello "},"finish_reason":null}]}',
        'data: {"choices":[{"delta":{"content":"world!"}}]}',
        'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}',
        'data: [DONE]',
    ]
    dropped_mid_stream = [
        'data: {"choices":[{"delta":{"content":"Partial answer..."}}]}',
    ]
    print("Healthy SSE evaluation:", evaluate_sse_session(http_status=200, raw_lines=healthy_sse))
    print("Mid-stream drop evaluation:", evaluate_sse_session(http_status=200, raw_lines=dropped_mid_stream))

Check /en/docs, /en/models, /en/pricing, and /en/providers/google to review streaming support and token pricing across models.

FAQ

Does using SSE streaming reduce Gemini API 429 rate-limit errors?

No. Streaming reduces time-to-first-token for the user, but each streaming request still consumes request (RPM) and token (input_TPM, RPD) quotas. Holding many long-lived streams open without a semaphore can actually increase concurrency pressure.

Should a client automatically retry when an SSE stream disconnects halfway through an answer?

No. Once partial tokens have been rendered to the user, silently firing a full retry duplicates the beginning of the response, confuses the UI, and spends input and output tokens twice. Only auto-retry pre-stream failures (HTTP 429/503 before tokens arrive) or zero-delta drops within your retry budget.

Why is checking HTTP 200 insufficient to mark a streaming call healthy?

In SSE streaming, HTTP 200 is sent before generation completes. A stream that sends keepalive comments or a usage-only chunk and closes without contentdeltas, a valid finish_reason, and data: [DONE] is an incomplete response.

Should structured JSON extraction pipelines use SSE streaming?

Only if a human user is watching a live preview. For background workers and database pipelines, standard non-streaming responses or complete buffered assembly before JSON Schema validation avoids partial-frame parsing bugs.

Sources & further reading

  1. Google Gemini API text generation and streaming guide
  2. Google Gemini API generateContent reference
  3. Google Gemini API OpenAI compatibility guide
  4. WHATWG HTML Standard: Server-Sent Events
  5. RFC 6585 section 4: 429 Too Many Requests
  6. API429 customer documentation: SSE streaming
  7. Current API429 public OpenAPI
  8. API429 public catalog contract

Put the next step into practice.

Check model IDs, current pricing and request formats before integrating. Availability can depend on the model and provider route.

Telegram