Twitter (X) to Apache Kafka: a Python Producer Keyed by Tweet ID

By TwitterAPI.io Team•15 min read
Diagram of a Twitter (X) to Apache Kafka pipeline. Box 1, twitterapi.io: GET /twitter/tweet/advanced_search with from:a OR from:b and since_time, following has_next_page and next_cursor. Box 2, the Python producer: a seen-id set, trim to about 0.6 KB, key equals tweet id, acks=all, idempotence on, gzip compression. Box 3, the Kafka topic x.tweets with 6 partitions and cleanup.policy compact,delete, where a hash of the key picks the partition. Box 4, consumers: sink to a table, search index, alerting, each in its own group.id, upsert on id. A curved arrow shows the checkpoint file storing the newest createdAt, saved after flush. Footer: measured on 1,400 tweets from 8 organization timelines and one keyword search, collected in 2026: median record 5.7 KB as returned, 556 bytes trimmed, largest 38.4 KB.
The producer sits between the X data API and the topic: it drops ids it has produced, trims each tweet, keys it by id and checkpoints only after the broker acknowledges. Diagram; footer numbers come from the study below.
TL;DR
  • Two feeds: poll /twitter/tweet/advanced_search with a since_time/until_time window, or receive filter-rule matches on the websocket and produce them as they arrive.
  • Key = tweet id. Same id, same partition: 1,400 distinct keys, every repeat of an id landed with its first copy in our local mock-cluster run.
  • Idempotence is not dedupe. It stops retry duplicates only; the consumer still saw all 20 repeated tweets we replayed. Drop seen ids in the producer and upsert on id in the sink.
  • Trim before producing: median record 5,701 bytes as returned vs 556 bytes trimmed (90% smaller); the largest of 1,400 tweets was 38,446 bytes, 3.7% of Kafka's 1 MB default.
  • Ask for new tweets only: re-reading the newest page every 60 s produced 95% to 100% duplicates and costs about $3.50 to $4.16 a day per source; a window query costs about $0.22.
  • Python default trap: confluent-kafka (librdkafka) defaults enable.idempotence to false and partitions with CRC32; set enable.idempotence=True and partitioner=murmur2_random.

This page is about the Kafka half of a tweet pipeline: the producer, the record key, the topic and the consumer that lands tweets in a table. If you are still choosing how to get a live feed of posts at all (filtered stream, webhooks, websockets, polling), start with our Twitter streaming API guide, and for full-volume firehose access see the Twitter firehose API developer guide. Here we assume you have a source of new posts and need them in Kafka, once each, in a shape downstream jobs can read.

The classic "Twitter Kafka producer" tutorials were written against X's older developer access and libraries such as Tweepy, with a free stream feeding the producer; today the official X API bills $0.005 per post read on its pay-per-usage rate card. The producer pattern itself still holds. What changes is the feed in front of it, plus three details the old tutorials skipped: what to use as the record key, how big a tweet really is as a Kafka value, and which producer defaults differ between the Python and Java clients.

Everything numeric below comes from a study we ran: 1,420 tweets returned by 73 API requests across 8 organization timelines and a kafka keyword search, collected in 2026, then replayed through confluent-kafka into librdkafka's in-process mock Kafka cluster on a laptop. No production broker was involved, so we report record sizes, duplicates, partition spread and API cost, and we do not report broker latency.

Median size of one tweet as a Kafka record

5,701 bytes as the API returns it vs 556 bytes trimmed to 18 fields (90.2% smaller), across 1,400 tweets collected in 2026; the largest was 38,446 bytes, 3.7% of Kafka's 1 MB default.

01 — Section

Two ways to feed Kafka from X: poll a window or hold a websocket

A Kafka producer for tweets is a loop with three jobs: get posts you have not produced yet, turn each one into a record, and hand it to the broker with a key. The only real design choice is the feed, and there are two that work without an X developer account.

Polling a time window. Every N seconds, call /twitter/tweet/advanced_search with your query plus since_time:<unix> and until_time:<unix> and queryType=Latest, follow has_next_page / next_cursor, and produce what comes back. The window moves forward only after the broker has acknowledged every record, so a crash re-reads the same window instead of losing it. An idle pass returns an empty tweets list and costs the $0.00015 minimum.

Push over a websocket. Register a filter rule once with /oapi/tweet_filter/add_rule (tag, value up to 255 characters, interval_seconds), switch it on with /oapi/tweet_filter/update_rule and is_effect: 1 (new rules start inactive, per the docs), then hold a connection to wss://ws.twitterapi.io/twitter/tweet/websocket with an x-api-key header. Matching tweets arrive as event_type: "tweet" messages carrying rule_id, rule_tag and a tweets array, and your handler produces each one. Nothing to schedule, but a connection to keep alive.

Polling a windowWebsocket push
Endpoint/twitter/tweet/advanced_searchfilter rule + wss://ws.twitterapi.io/...
You runa loop or cron jobone long-lived process
Restart safetyre-read the last windowrule keeps running; reconnect after 5 s or more
Connectionsany number of pollersone websocket per API key
Good forbatch-friendly feeds, backfillslow-delay alerting topics

The websocket guide in our docs (docs.twitterapi.io/websocket-stream) is strict about connections: one websocket per API key, a new connection replaces the old one (close code 4001), no more than one handshake per key every 5 seconds (4029), and a key that keeps reconnecting from two places is refused for 60 seconds up to 10 minutes (4009). Run exactly one websocket producer per key. If you need two consumers of the feed, that is what Kafka is for: produce once, read with as many consumer groups as you like. For the websocket mechanics in isolation see using websockets for real-time Twitter data.

02 — Section

What one tweet weighs as a Kafka record

A tweet object as the API returns it is not small. We serialized every returned tweet exactly as received (compact JSON, UTF-8) and measured it as a Kafka value would be measured before compression. Across 1,400 unique tweets the median was 5,701 bytes, the 95th percentile 18,552 bytes and the largest 38,446 bytes. A trimmed record with 18 fields that downstream jobs typically read (id, time, author id and handle, text, language, the five counters, conversation and reply ids, URLs, hashtags, media types, quoted and retweeted ids) had a median of 556 bytes: 90.2% smaller.

SourceTweetsMedian as returnedMedian trimmedgzip ratio, 20-tweet batch
@Reuters16017,772 B451 B17.6x
@vercel1609,978 B607 B12.2x
@NASA1606,796 B507 B7.9x
@OpenAI1605,782 B652 B9.1x
@apachekafka1473,123 B496 B8.0x
search: kafka1602,778 B478 B6.1x

Two things inflate a record. Nested objects: a tweet carrying a quoted_tweet or retweeted_tweet embeds a second full tweet, and for @apachekafka those records had a median of 6,633 bytes against 2,257 bytes for plain ones. And card / media payloads, which is why @Reuters, whose posts are link cards, sits at about 17.8 KB per tweet as returned while its trimmed record is the smallest in the table.

Size matters for three settings. The topic limit max.message.bytes defaults to 1,048,588 bytes in Kafka 4.4 and the Java producer's max.request.size to 1,048,576; our largest tweet used 3.7% of that, and none of 1,400 came close, so you do not need to raise either for tweets. The producer's batch.size (16,384 bytes by default in the Java client) holds only two or three full tweets but about 29 trimmed records. And compression: full tweet JSON compressed 6.1x to 17.6x per 20-tweet batch with gzip, trimmed records 2.9x to 3.5x, because the repeated author and entity blocks are what gzip squeezes. Trimming first still wins on bytes stored and bytes every consumer must parse.

Dot plot of Kafka record value size per source in KB. For each of nine sources, a blue dot marks the median trimmed record (all near 0.5 KB) and an orange dot the median full tweet object as returned, with a dotted line to the 95th percentile. Medians as returned: @Reuters 17.8 KB, @vercel 10.0 KB, @NASA 6.8 KB, @nvidia 6.1 KB, @OpenAI 5.8 KB, @github 5.4 KB, @confluentinc 4.3 KB, @apachekafka 3.1 KB, search kafka 2.8 KB. Subtitle: median 5,701 bytes as returned vs 556 bytes trimmed across 1,400 tweets; largest 38,446 bytes, 3.7% of Kafka's 1 MB default.
Median record size per source, full tweet object as returned vs an 18-field trimmed record (1,400 tweets, collected in 2026).
03 — Section

Producer settings that matter, and the Python default trap

Kafka's own producer docs (Kafka 4.4) list acks=all and enable.idempotence=true as defaults for the Java client, with compression.type=none, linger.ms=5 and keyed records partitioned by a hash of the key. The Python client confluent-kafka (2.16.2 on PyPI, built on librdkafka) does not share all of those defaults. librdkafka's configuration reference lists enable.idempotence as false by default and its default partitioner as consistent_random, a CRC32 hash of the key, while murmur2_random is described as functionally equivalent to the Java producer's default.

SettingJava client defaultlibrdkafka (Python) defaultSet for tweets
enable.idempotencetruefalsetrue
acksall-1 (all)all
compression.typenonenonegzip, lz4 or zstd
linger.ms5520 to 100
key partitionermurmur2 hashCRC32 (consistent_random)murmur2_random

The partitioner line is the one that bites later. If a Java or Kafka Streams job and a Python producer write to the same topic with the same keys, the CRC32 default puts tweet 123 on a different partition than the Java client would, and anything that relies on same-key-same-partition (compaction, per-key ordering, a co-partitioned join) quietly breaks. Setting partitioner=murmur2_random in Python lines the two up.

linger.ms and compression are throughput settings, and a tweet feed is a small stream: our busiest source, a kafka keyword search, peaked at 54 tweets in an hour and 4 in a minute. A 50 ms linger costs nothing noticeable and lets the producer batch a page of 20 tweets into one compressed request.

python
from confluent_kafka import Producer

producer = Producer({
    "bootstrap.servers": "localhost:9092",
    "enable.idempotence": True,        # librdkafka default: false. Java client default: true
    "acks": "all",                     # required by idempotence; already the default in both
    "compression.type": "gzip",        # default none; tweet JSON batches compress 6x to 18x
    "linger.ms": 50,                   # wait up to 50 ms to fill a batch (default 5)
    "partitioner": "murmur2_random",   # default consistent_random (CRC32); murmur2 matches Java
})
04 — Section

Key by tweet id: what the key buys you, and what idempotence does not

Use the tweet id as the record key, as bytes of its decimal string. It is globally unique, it is present on every tweet object, and a key gives you three things Kafka only offers for keyed records: every copy of a tweet lands on the same partition, consumers see a tweet's copies in order, and a topic with cleanup.policy=compact (or compact,delete) eventually keeps only the latest record per tweet.

We checked the first two locally. We replayed all 1,420 returned tweets (1,400 distinct ids; @nvidia's timeline returned one page of 20 ids twice) through the trimmed-record producer into librdkafka's in-process mock cluster of 3 brokers, with enable.idempotence=True, acks=all, gzip and murmur2_random, then read the topic back with a consumer.

Check (local mock cluster)Result
Records produced / delivered / delivery errors1,420 / 1,420 / 0
Distinct keys1,400
Every copy of a key on one partitionyes
Records per partition (4 partitions)358 / 357 / 368 / 337
Repeated tweet ids the consumer received20 (20 extra copies)

The last row is the point. Idempotence protects against the producer's own retries: if a send times out and is retried, the broker drops the second copy. It does not know that two different produce() calls carry the same tweet, so a poller that re-reads tweets it already produced writes them again, and every consumer sees them. Log compaction would eventually remove older copies, but on its own schedule and never for a consumer that already read them. So dedupe twice: a seen-id set in the producer (the main code below keeps the last 5,000 ids in its checkpoint file) and an upsert on tweet id in every sink.

Tweet ids also hash evenly: with 1,400 keys over 4 partitions the fullest partition held 3.7% more than the mean and the emptiest 5.1% less. You do not need a custom partitioner for tweets.

05 — Section

Polling producer: ask only for tweets you have not seen

The tempting first version of a polling producer reads an account's newest page with /twitter/user/last_tweets every minute and produces whatever comes back. We modeled that against the real timestamps of each source's newest 100 tweets. At a 60-second interval it produces 95.4% to 100% duplicates, because organization accounts post a few times a day while the newest page always holds 20 tweets. Even the busiest source, the kafka keyword search at about 1,223 tweets a day, was 95.4% duplicates.

It also costs more. A full 20-tweet page is $0.003 (15 credits per tweet returned), so re-reading it every minute comes to about $3.50 to $4.16 a day per source. A since_time window query that returns only new tweets costs the 15-credit minimum when it finds nothing, about $0.22 a day at a 60-second interval, $0.29 for the busy keyword search: 14x to 19x less.

SourceTweets a day (newest 100)Naive duplicates at 60 sNaive $/dayWindow query $/day
search: kafka1,222.895.4%$4.00$0.29
@Reuters264.099.0%$3.81$0.22
@NASA3.299.99%$3.83$0.22
@confluentinc0.4100.0%$4.07$0.22

Two more things showed up in the raw pages. Timelines are not strictly newest-first: 4 of the 8 timelines (@github, @OpenAI, @nvidia, @NASA) returned at least one tweet older than the one after it, so take the newest createdAt across the page rather than the first tweet. And one timeline returned a page of 20 ids that we had already received, which the seen-id set absorbs. The main code at the end of this page uses a closed window, since_time to until_time 30 seconds in the past, and only moves the window after flush() returns 0.

For a scheduled version of the same job (Airflow, cron, a container that runs once and exits), the window-and-checkpoint pattern carries over unchanged; the Twitter API with Airflow guide shows it as a DAG.

Horizontal bar chart of modeled API cost per day per source when polling every 60 seconds. Orange bars, re-reading the newest 20-tweet page every poll: @Reuters $3.81 (98.96% duplicates), @vercel $3.50 (100.00%), @NASA $3.83 (99.99%), @nvidia $4.16 (99.99%), @OpenAI $3.94 (100.00%), @github $3.93 (99.99%), @confluentinc $4.07 (100.00%), @apachekafka $3.99 (100.00%), search kafka $4.00 (95.42%). Blue bars, advanced_search with since_time returning only new tweets: $0.22 for each account, $0.29 for search kafka.
Modeled API cost per source per day at a 60-second poll: re-reading the newest page vs asking only for new tweets (timestamps collected in 2026; 15 credits per tweet returned, 15-credit minimum per request).
06 — Section

Push producer: filter-rule matches from the websocket into Kafka

With an active filter rule, the producer becomes an event handler. Each tweet event carries a tweets array; produce every tweet keyed by its id and put the rule's tag in a record header, so one topic can carry several rules and consumers can filter without parsing the value. The connected and ping events (a ping arrives about every 20 seconds, per the docs) need no reply.

Reconnect rules come straight from the websocket guide: after an ordinary disconnect wait at least 5 seconds before the next handshake, and on 4001 (replaced), 4003 (bad key) or 4009 (key in use elsewhere) stop instead of retrying, because another client owns the key or the key is wrong. On 4029 wait the Retry-After period. The code below uses a fixed 10-second wait between attempts and exits on the three stop codes.

Two cautions. This handler produces the full tweet object (median 5.7 KB in our sample); swap in the trim() function from the main code if your consumers do not need every field. And the websocket guide does not describe replaying matches missed while you were disconnected, so if a gap matters, run the polling producer for the missed window after a reconnect, which the shared seen-id logic and the upsert sink make safe. We compiled this script but did not run it against a live rule for this page; the polling producer and the sink were run against the mock cluster.

python
"""ws_to_kafka.py - push path: tweets matched by your active filter rules arrive on the
twitterapi.io websocket and are produced to Kafka, keyed by tweet id.

    pip install websocket-client confluent-kafka
    export TWITTERAPI_IO_API_KEY=...
    python ws_to_kafka.py
"""
import json
import os
import time

import websocket
from confluent_kafka import Producer

X_KEY = os.environ["TWITTERAPI_IO_API_KEY"]
WS_URL = "wss://ws.twitterapi.io/twitter/tweet/websocket"
TOPIC = "x.tweets"
STOP_CODES = {4001, 4003, 4009}   # replaced by another client, bad key, key in use elsewhere

producer = Producer({
    "bootstrap.servers": os.environ.get("KAFKA_BOOTSTRAP", "localhost:9092"),
    "enable.idempotence": True,
    "acks": "all",
    "compression.type": "gzip",
    "linger.ms": 50,
    "partitioner": "murmur2_random",
})
stop = {"code": None}


def on_message(ws, raw):
    event = json.loads(raw)
    kind = event.get("event_type")
    if kind == "tweet":
        for t in event.get("tweets") or []:
            producer.produce(TOPIC, key=str(t["id"]).encode(),
                             value=json.dumps(t, separators=(",", ":")).encode(),
                             headers={"rule_tag": str(event.get("rule_tag", ""))})
        producer.poll(0)
    elif kind == "error":
        print("refused:", event.get("error_code"), event.get("message"))


def on_close(ws, code, reason):
    stop["code"] = code
    producer.flush(30)


while True:
    ws = websocket.WebSocketApp(WS_URL, header={"x-api-key": X_KEY},
                                on_message=on_message, on_close=on_close)
    ws.run_forever(ping_interval=30, ping_timeout=10)
    if stop["code"] in STOP_CODES:
        print("stopping, close code", stop["code"])
        break
    time.sleep(10)   # fixed wait: the docs ask for at least 5 s between handshakes per key
07 — Section

Topic design and a consumer that lands tweets in a table

Partitions. Partitions set how many consumers in one group can work in parallel, not how much a tweet feed can carry. Our busiest sampled source peaked at 54 tweets in an hour; a few partitions (3 to 6) leave room for parallel sinks, and you can add partitions later, but that changes which partition some keys hash to, so settle the count before you rely on per-key order.

Retention and cleanup. Kafka's topic default is cleanup.policy=delete with retention.ms of 604,800,000 (7 days). For a tweet topic that consumers replay to rebuild tables, cleanup.policy=compact,delete keeps the latest record per tweet id and still drops old segments by time. Public engagement counters change after posting, so a later re-fetch of the same tweet with fresh likeCount and viewCount naturally replaces the older record under compaction.

Record timestamp. Pass the tweet's createdAt as the record timestamp (timestamp= in milliseconds on produce()), so stream processors and time-based lookups see when the post was written, not when your poller ran.

The sink. The consumer below disables auto-commit, writes each record into SQLite with INSERT ... ON CONFLICT(id) DO UPDATE, and commits the offset only after the row is written. That gives at-least-once delivery, and the upsert makes replays and duplicates harmless. Swap SQLite for your warehouse: the same upsert works in Postgres (see Twitter API to PostgreSQL), and a Kafka connector or Snowpipe-style loader can replace the script for Snowflake or Databricks. In our mock-cluster run this consumer, fed by the polling producer replaying a 160-tweet timeline with 20 repeated ids, ended with 140 rows.

python
"""consumer_sink.py - read x.tweets and upsert each tweet into a table keyed by tweet id.

    pip install confluent-kafka
    python consumer_sink.py
"""
import json
import os
import sqlite3

from confluent_kafka import Consumer

consumer = Consumer({
    "bootstrap.servers": os.environ.get("KAFKA_BOOTSTRAP", "localhost:9092"),
    "group.id": "tweet-sink",
    "auto.offset.reset": "earliest",
    "enable.auto.commit": False,       # commit only after the row is written
})
consumer.subscribe([os.environ.get("KAFKA_TOPIC", "x.tweets")])

db = sqlite3.connect(os.environ.get("SINK_DB", "tweets.db"))
db.execute("""CREATE TABLE IF NOT EXISTS tweets (
    id TEXT PRIMARY KEY, created_at TEXT, author TEXT, text TEXT,
    likes INTEGER, views INTEGER, record TEXT)""")

UPSERT = """INSERT INTO tweets (id, created_at, author, text, likes, views, record)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET likes = excluded.likes, views = excluded.views,
    record = excluded.record"""

try:
    while True:
        msg = consumer.poll(1.0)
        if msg is None:
            continue
        if msg.error():
            print("consumer error:", msg.error())
            continue
        t = json.loads(msg.value())
        db.execute(UPSERT, (t["id"], t["created_at"], t["author"], t["text"],
                            t["likes"], t["views"], msg.value().decode()))
        db.commit()
        consumer.commit(message=msg, asynchronous=False)   # at-least-once; the upsert absorbs replays
finally:
    consumer.close()
    db.close()
08 — Section

Cost of a tweet feed into Kafka: twitterapi.io vs the official X API

Kafka itself does not change the data bill; what you pay for is the posts your producer reads. twitterapi.io charges 15 credits per tweet returned, $0.15 per 1,000 tweets, with a 15-credit ($0.00015) minimum per request, and needs no X developer account for reads. The official X API's pay-per-usage rate card (docs.x.com/x-api/getting-started/pricing) lists $0.005 per post read and $0.010 per user read, with pay-per-usage capped at 3 million post reads per monthly billing cycle and Enterprise above that.

Feedtwitterapi.ioOfficial X API (pay-per-usage)
1,000 tweets produced$0.15$5.00
Idle poll every 60 s, 30 days$6.48billed per post read
A @Reuters-like feed, 264 tweets a day, 30 daysabout $1.19 for tweets + polling floorabout $39.60
Volume ceilingno monthly cap3M post reads a month, then Enterprise

Per 1,000 tweets that is about 33x less ($5.00 / $0.15). The polling floor is the part people forget: a 60-second window query that finds nothing still costs $0.00015, which is $6.48 over a 30-day month; every 5 minutes it is $1.30. If a topic only needs a few posts a day, poll less often or use the push path. New accounts get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the amount and for paid plans. Paid accounts get 20 requests per second (0.2 before the first payment), far above what a tweet producer needs.

09 — Section

How we collected this

Question. What does a Twitter (X) to Kafka producer actually carry: how many records per hour, how large each record is as a Kafka value, how well batches compress, how close any record gets to Kafka's 1 MB default, how many duplicates a naive poller produces, and whether tweet-id keys behave in a real Kafka client.

Accounts and query. Eight organization timelines via /twitter/user/last_tweets (@apachekafka, @confluentinc, @github, @vercel, @OpenAI, @nvidia, @NASA, @Reuters), up to 8 pages each, plus /twitter/tweet/advanced_search for kafka with queryType=Latest, 9 pages. Window: each source's recent posts at collection time, collected in 2026.

Sample size and cost. 73 requests, 1,420 tweets returned, 1,400 unique; API cost $0.213. Record size is the UTF-8 length of the compact JSON of each tweet. The gzip ratio is the median over consecutive 20-tweet batches at level 6. Duplicate shares and daily costs are modeled from the newest 100 tweets' timestamps of each source, at 15 credits per tweet returned and the 15-credit minimum.

Local Kafka step. All 1,420 returned tweets were replayed through confluent-kafka 2.16.2 (librdkafka 2.16.0) into librdkafka's in-process mock cluster (test.mock.num.brokers=3; the auto-created topic had 4 partitions), then consumed back; the polling producer and SQLite sink on this page were run the same way with the API call replaced by a recorded timeline.

What the sample cannot show. Broker latency, disk use, compaction timing or behavior under a real cluster's load: the mock cluster runs in memory and has no log cleaner. Delivery delay from a post being written to it reaching Kafka was not measured. Organization accounts post far less than a busy keyword, so rates per source are examples, not benchmarks.

Privacy. Only organization accounts are named. The keyword search returned posts by private individuals; its raw pages stayed on the collection machine and only aggregates and de-identified rows (no ids, URLs, text or handles) were kept.

python
"""x_to_kafka.py - poll twitterapi.io for new X (Twitter) posts and produce them to Apache Kafka,
keyed by tweet id, advancing the checkpoint only after the broker acknowledged every record.

    pip install requests confluent-kafka
    export TWITTERAPI_IO_API_KEY=...          # twitterapi.io dashboard
    export KAFKA_BOOTSTRAP=localhost:9092
    python x_to_kafka.py                      # runs forever, one pass every 60 s

Cost: one advanced_search call per pass. A pass that finds nothing costs the $0.00015 minimum
(15 credits); each tweet returned costs 15 credits ($0.15 per 1,000). Every 60 s that floor is
about $0.22 a day.
"""
import json
import os
import time
from datetime import datetime

import requests
from confluent_kafka import Producer

API = "https://api.twitterapi.io"
X_KEY = os.environ["TWITTERAPI_IO_API_KEY"]
TOPIC = os.environ.get("KAFKA_TOPIC", "x.tweets")
QUERY = os.environ.get("X_QUERY", "(from:apachekafka OR from:confluentinc OR from:Reuters)")
INTERVAL = 60          # fixed pacing between passes, in seconds
LAG = 30               # each window ends 30 s in the past, so late-indexed posts are not skipped
MAX_PAGES = 10         # safety cap per pass (one page = up to 20 tweets = $0.003)
STATE_FILE = "x-kafka-checkpoint.json"

producer = Producer({
    "bootstrap.servers": os.environ.get("KAFKA_BOOTSTRAP", "localhost:9092"),
    "enable.idempotence": True,        # librdkafka defaults this to false; the Java client to true
    "acks": "all",
    "compression.type": "gzip",
    "linger.ms": 50,
    "partitioner": "murmur2_random",   # same key -> partition mapping as Java clients
})


def load_state():
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE) as f:
            return json.load(f)
    return {"since": int(time.time()) - 3600, "seen": []}   # first run: the last hour


def save_state(state):
    state["seen"] = state["seen"][-5000:]
    tmp = STATE_FILE + ".tmp"
    with open(tmp, "w") as f:
        json.dump(state, f)
    os.replace(tmp, STATE_FILE)        # atomic: a crash never leaves half a checkpoint


def created_ms(tweet):
    dt = datetime.strptime(tweet["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    return int(dt.timestamp() * 1000)


def trim(tweet):
    """About 0.6 KB instead of about 5.7 KB: keep what downstream jobs read."""
    author = tweet.get("author") or {}
    entities = tweet.get("entities") or {}
    media = (tweet.get("extendedEntities") or {}).get("media") or []
    return {
        "id": tweet["id"],
        "created_at": tweet.get("createdAt"),
        "author_id": author.get("id"),
        "author": author.get("userName"),
        "text": tweet.get("text"),
        "lang": tweet.get("lang"),
        "likes": tweet.get("likeCount"),
        "retweets": tweet.get("retweetCount"),
        "replies": tweet.get("replyCount"),
        "quotes": tweet.get("quoteCount"),
        "views": tweet.get("viewCount"),
        "conversation_id": tweet.get("conversationId"),
        "in_reply_to_id": tweet.get("inReplyToId"),
        "urls": [u.get("expanded_url") for u in entities.get("urls") or []],
        "hashtags": [h.get("text") for h in entities.get("hashtags") or []],
        "media": [m.get("type") for m in media],
        "quoted_id": (tweet.get("quoted_tweet") or {}).get("id"),
        "retweeted_id": (tweet.get("retweeted_tweet") or {}).get("id"),
    }


def fetch_window(since, until):
    """Every tweet matching QUERY created in [since, until), following next_cursor."""
    tweets, cursor = [], None
    q = f"{QUERY} since_time:{since} until_time:{until}"
    for _ in range(MAX_PAGES):
        params = {"query": q, "queryType": "Latest"}
        if cursor:
            params["cursor"] = cursor
        r = requests.get(f"{API}/twitter/tweet/advanced_search",
                         headers={"X-API-Key": X_KEY}, params=params, timeout=30)
        r.raise_for_status()
        body = r.json()
        tweets.extend(body.get("tweets") or [])
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return tweets


failed = []


def on_delivery(err, msg):
    if err is not None:
        failed.append((msg.key(), str(err)))


def run_once(state):
    until = int(time.time()) - LAG
    tweets = fetch_window(state["since"], until)
    seen = set(state["seen"])
    fresh = []
    for t in tweets:
        tid = str(t["id"])
        if tid in seen:            # boundary or page repeats: never produce the same id twice
            continue
        seen.add(tid)
        fresh.append(tid)
        producer.produce(TOPIC, key=tid.encode(),
                         value=json.dumps(trim(t), separators=(",", ":")).encode(),
                         timestamp=created_ms(t), on_delivery=on_delivery)
        producer.poll(0)
    left = producer.flush(30)
    if left or failed:
        n = len(failed)
        failed.clear()
        raise RuntimeError(f"{left} records unflushed, {n} failed; checkpoint not advanced")
    state["since"] = until
    state["seen"] = state["seen"] + fresh
    save_state(state)
    return len(fresh)


if __name__ == "__main__":
    state = load_state()
    while True:
        try:
            n = run_once(state)
            print(f"produced {n} new tweets, window now starts at {state['since']}")
        except (requests.RequestException, RuntimeError) as e:
            print("pass failed, will retry the same window:", e)
        time.sleep(INTERVAL)

Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.

10 — Questions

Questions readers ask

Can I still stream tweets into Kafka for free?

Not through X's own API: its pay-per-usage rate card bills $0.005 per post read, so the free stream that old Kafka tutorials relied on is not an option today. A third-party X data API is the usual route now; on twitterapi.io reads cost $0.15 per 1,000 tweets with no X developer account, and new accounts get free starter credits (see /pricing for the amount).

Which Python Kafka client should I use for a tweet producer?

confluent-kafka (pip install confluent-kafka; 2.16.2 on PyPI, built on librdkafka, Python 3.9 or later) is the client the code on this page uses and was run against. Whichever client you choose, set enable.idempotence=True and acks=all explicitly rather than trusting defaults, and match the partitioner to any Java clients on the same topic.

What should the Kafka record key be for tweets?

The tweet id as a string, encoded to bytes. It is unique, always present, and keyed records give you same-partition placement for every copy of a tweet, per-key ordering, and log compaction down to the latest record per tweet. In our 1,400-tweet local run every repeated id landed on the same partition as its first copy.

Does enable.idempotence remove duplicate tweets?

No. It drops duplicates caused by the producer retrying a send. Two separate produce() calls with the same tweet are two records; in our run the consumer received all 20 repeated tweets. Keep a seen-id set in the producer and upsert on tweet id in the sink.

Will a tweet ever exceed Kafka's message size limit?

Not in our sample. Kafka 4.4's topic default max.message.bytes is 1,048,588 bytes; the largest of 1,400 tweets, a full object with nested quoted content, was 38,446 bytes (3.7%). The median was 5,701 bytes as returned and 556 bytes trimmed.

How many partitions does a Twitter topic need?

Few. Partitions limit how many consumers in a group can work in parallel, and tweet feeds are small: the busiest source we sampled, a keyword search for kafka, peaked at 54 tweets in an hour. Three to six partitions leave room for parallel sinks; tweet-id keys spread evenly (within about 5% of the mean over 4 partitions in our run).

Polling or websocket: which should feed my producer?

Poll a since_time/until_time window when you want restart safety and simple scheduling: a crash just re-reads the window, and an idle pass costs $0.00015. Use the filter-rule websocket when delay matters more; it allows one connection per API key, so run one websocket producer and fan out through Kafka consumer groups.

Can I use Kafka Connect instead of a Python producer?

Kafka Connect is a good fit for the sink side (tweets to Postgres, S3, Snowflake or a search index), where connectors handle offsets and retries. For the source side, a small producer like the one here is the simple path: about a hundred lines, and you can run it next to Connect and let sink connectors read the topic.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.