Twitter Streaming API Guide: WebSocket vs REST vs Filtered Stream (2026)

How Twitter's streaming API works — filtered stream endpoints, WebSocket alternatives, and code examples for real-time alerts.

What Is the Twitter Streaming API?

The Twitter streaming API (now the X API) lets developers receive tweets in real time as they are posted, rather than polling an endpoint on a schedule. For trading bots, news aggregators, social listening dashboards, and any application where latency matters, streaming is the foundation of a responsive pipeline.

X's v2 API exposes two streaming endpoints: the filtered stream, which delivers tweets matching developer-defined rules, and the sampled stream, which returns a roughly 1 % random sample of all public tweets. Both use long-lived HTTP connections — the server holds the connection open and pushes newline-delimited JSON objects as matching tweets appear.

Historically, Twitter offered earlier streaming surfaces in v1.1. The specific packaging and entitlements around today's X API should always be verified in the current docs and your account console.

How the Streaming Protocol Works Under the Hood

The X streaming API does not use WebSockets. Instead, it relies on HTTP streaming — a long-lived HTTP/1.1 (or HTTP/2) connection where the server sends data incrementally without closing the response. Think of it as downloading an infinitely long file.

Your client opens an HTTP GET request to the filtered stream endpoint. The server responds with status 200 and begins writing newline-delimited JSON. Each tweet arrives as a single line. Between tweets, X sends keep-alive newlines (empty lines) roughly every 20 seconds so your client can detect stalled connections.

This design has consequences. Your HTTP client must support chunked transfer encoding and incremental parsing. Standard request/response libraries (like fetch or axios) buffer the full response before returning it, which defeats the purpose. You need a streaming HTTP client — such as Node.js's built-in http module, Python's requests with stream=True, or a library like undici.

  • Protocol: HTTP/1.1 chunked transfer encoding (not WebSocket)
  • Format: Newline-delimited JSON, one tweet per line
  • Keep-alive: Empty newlines every ~20 seconds
  • Reconnect: Client responsible for detecting drops and retrying with backoff

Streaming vs Polling vs WebSocket: A Latency Comparison

Polling (REST) means your app hits a search or timeline endpoint on a timer. You spend requests whether there is new data or not, and your worst-case latency is bounded by your poll interval.

HTTP streaming (X's filtered stream) pushes tweets as they match your rules. It reduces polling overhead, but you still need to verify current access, handle reconnects, and work with raw tweet JSON.

WebSocket delivery also pushes data in real time but over a persistent, bidirectional connection. WebSocket is a separate protocol (RFC 6455) that begins as an HTTP upgrade and then switches to a framed binary/text protocol. It supports server push, client push, ping/pong keep-alives, and built-in close handshakes — none of which HTTP streaming provides.

FeatureREST PollingHTTP Streaming (X API)WebSocket
Typical latencyPoll interval dependentPush-based; depends on providerPush-based; depends on provider
ProtocolHTTP request/responseHTTP chunked transferWebSocket (RFC 6455)
DirectionClient pullsServer pushesBidirectional
ReconnectionNot neededManual backoff requiredApplication-managed reconnect on socket close
Keep-aliveN/AEmpty newlines ~20sPing/pong frames
Minimum X tierCheck current docsCheck current docsN/A (third-party)
EnrichmentNoneNoneDepends on provider

The Filtered Stream Endpoint in Detail

The filtered stream (POST /2/tweets/search/stream/rules to set rules, GET /2/tweets/search/stream to connect) is X's primary real-time endpoint. You define up to 1,000 rules (at Enterprise tier) using a boolean query language similar to the search endpoint.

Each rule can match on keywords, usernames, hashtags, conversation IDs, and more. When a public tweet matches any rule, it appears in your stream with the matching rule IDs attached.

Key limitations to know:

  • Rule and connection limits depend on the access level attached to your account
  • No historical backfill — you only get tweets posted while connected
  • Disconnections can lose data unless you have a recovery path
  • Operational limits are part of the product decision, not just the protocol decision

Code Example: Connecting to X Filtered Stream (Node.js)

// Connect to X API filtered stream
const needle = require('needle');

const BEARER_TOKEN = process.env.X_BEARER_TOKEN;
const STREAM_URL = 'https://api.x.com/2/tweets/search/stream';

async function streamConnect() {
  const response = await needle('get', STREAM_URL, {
    headers: {
      Authorization: `Bearer ${BEARER_TOKEN}`,
    },
  });

  response.on('data', (data) => {
    try {
      const json = JSON.parse(data);
      console.log('[TWEET]', json.data?.text);
    } catch (e) {
      // Keep-alive newline — ignore
    }
  });

  response.on('err', (error) => {
    console.error('Stream error:', error);
    // Implement exponential backoff before reconnecting
    setTimeout(streamConnect, 5000);
  });
}

streamConnect();

X API Streaming Access by Tier (April 2026)

Use the current X docs and Developer Console to confirm how streaming access is packaged for your account today:

TierMonthly CostTweet Read CapStreaming AccessRules
Pay-per-useUsage-basedCheck X docsCheck current entitlementCheck current entitlement
Legacy fixed plansLegacy / opt-inCheck X docsCheck current entitlementCheck current entitlement
EnterpriseContact salesCustomCustomCustom

Treat old screenshots and pricing roundup posts as historical context only. Confirm current entitlements directly before you design around them.

Always confirm current pricing at the official X API documentation — tiers and limits change frequently.

Code Example: TweetStream WebSocket Connection

// Connect to TweetStream WebSocket (from $199/mo)
const WS_URL = 'wss://ws.tweetstream.io/ws';
const API_KEY = process.env.TWEETSTREAM_API_KEY;

const ws = new WebSocket(WS_URL, [
  'tweetstream.v1',
  `tweetstream.auth.token.${API_KEY}`,
]);

ws.onmessage = (event) => {
  const envelope = JSON.parse(event.data);

  if (envelope.t === 'tweet' && envelope.op === 'content') {
    const { author, text } = envelope.d;
    console.log(`[${author.handle}] ${text}`);
  }

  if (envelope.t === 'tweet' && envelope.op === 'meta') {
    const { tokens, ocrTexts } = envelope.d;
    if (tokens?.length) {
      console.log('Detected tokens:', tokens.map(t => t.symbol));
    }
  }
};

WebSocket Alternatives to the Twitter Streaming API

If you need low-latency monitored-account alerts without owning the full streaming pipeline, WebSocket-based services offer an alternative. These services handle the data pipeline and deliver tweets over a persistent WebSocket connection with additional enrichment.

TweetStream, for example, delivers tweet alerts in ~200 ms with automatic token detection, OCR text extraction from images, and live cryptocurrency prices — features you would need to build yourself on top of the raw X API.

  • Push-based delivery with ~200 ms typical latency
  • Persistent WebSocket connection with automatic reconnection
  • No streaming infrastructure to build or maintain
  • Built-in enrichment: OCR, token detection, live prices, Polymarket odds
  • Starts at $199/month

When to Use a Streaming Alternative

Consider a WebSocket alternative when:

  • You need sub-second delivery for trading or alerting
  • You want enriched data (tokens, prices, OCR) without building pipelines
  • Official API packaging or operational overhead is not a fit
  • You do not want to manage reconnection logic and backfill
  • You need specific account monitoring rather than keyword-based rules

Frequently Asked Questions

Next Steps

If you need streaming alerts with enrichment like token detection or OCR, start with the WebSocket quickstart. For a detailed comparison with the official X API, see our Twitter API alternative page.

TweetStream Team

Last updated: April 2026

Start real-time Twitter WebSocket alerts today

WebSocket delivery, OCR, and token detection - no infrastructure to build.

Start 7-Day Trial

From $199/mo · Basic/Elite 7-day trial · OCR + token detection included

Related Pages