> ## Documentation Index
> Fetch the complete documentation index at: https://docs.x.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Streaming in Ruby XDK

> Consume X API v2 real-time streams in Ruby with keep-alive callbacks, idle-timeout recovery, and automatic reconnection.

Streaming endpoints yield parsed JSON events as they arrive (or return a lazy `Enumerator` when called without a block), with automatic exponential backoff reconnection, keep-alive heartbeat callbacks, and optional idle-timeout stall detection.

## Consuming a stream

```ruby theme={null}
require "xdk"

client = Xdk::Client.new(bearer_token: ENV.fetch("X_BEARER_TOKEN"))

config = Xdk::StreamConfig.new(
  max_retries: -1,           # -1 for infinite retries
  initial_backoff: 1.0,
  max_backoff: 64.0,
  idle_timeout: 60.0,        # reconnect if no data or 20s heartbeat arrives for 60s
  reconnect_on_close: true,
  on_connect: -> { puts "Stream connected" },
  on_keep_alive: -> { puts "Heartbeat received" },
  on_reconnect: ->(attempt, delay) { warn "Reconnecting ##{attempt} in #{delay.round(2)}s" },
  on_error: ->(err) { warn "Stream error (#{err.error_type}): #{err.message}" }
)

client.stream.posts(stream_config: config) do |event|
  puts event.dig("data", "text")
end
```

## Error classification

* **Retryable (`err.retryable? == true`):** connection resets, timeouts (`Xdk::StreamIdleTimeoutError`), `429` rate limits, and `5xx` server errors — retried automatically with exponential backoff and jitter, resetting the backoff counter whenever an event or keep-alive heartbeat arrives.
* **Non-retryable (`err.retryable? == false`):** `401` / `403` authentication errors and other `4xx` client errors raise `Xdk::StreamError` immediately.
