Twitter 流式 API 指南:WebSocket vs REST vs 过滤流 (2026)

2026 年 Twitter 流式 API 工作原理 — 过滤流端点、WebSocket 替代方案、代码示例与实时提醒延迟基准测试。

什么是 Twitter 流式 API?

Twitter 流式 API(现为 X API)让开发者在推文发布瞬间接收数据,而不是轮询。对交易机器人、新闻聚合和低延迟场景尤为重要。

X 提供不同层级的流式访问。过滤流和采样流端点可订阅匹配规则的推文或随机样本。

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

流式 vs 轮询:为什么重要

轮询 指应用按固定间隔查询新推文(如每 5 秒)。这会带来固有延迟并浪费调用。

流式 会在推文匹配过滤条件时立即推送。对市场敏感提醒,可能决定是否错过信号。

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 流式层级与权限

X 在开发者平台列出访问层级与端点。流式权限取决于层级:

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

构建前请在 官方 X API 文档 中确认当前定价与限制。

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));
    }
  }
};

Twitter 流式 API 的 WebSocket 替代方案

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.

  • 推送式交付避免轮询延迟
  • 稳定连接适合交易流程
  • 无需维护基础设施或重连逻辑
  • 内置代币检测与 OCR 富化

何时选择流式 API 替代方案

以下场景可考虑 WebSocket 替代方案:

  • 需要亚秒级交付
  • 希望获得富化数据(代币、价格、OCR)
  • 不想维护流式基础设施
  • X API 定价或限制不匹配

Frequently Asked Questions

下一步

需要带富化的实时提醒?先看 WebSocket 快速开始。想对比官方 X API,请看 Twitter API 替代方案

TweetStream 团队

最近更新:2026 年 1 月

立即开启实时 Twitter WebSocket 提醒

内置 WebSocket 交付、OCR 与代币检测的 Twitter API 替代方案。

开始 7 天试用

起价 $199/月 · Basic/Elite 含 7 天试用 · OCR + 代币检测

相关页面