Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils

By TwitterAPI.io Team•14 min read
Flow diagram of a Twitter (X) to Apache Spark Structured Streaming pipeline without TwitterUtils: X search via /twitter/tweet/advanced_search, a Python poller, a landing zone of JSON-lines files or a Kafka topic, Spark readStream with watermark and 5-minute windows, and a Parquet or Delta sink.
Twitter (X) into Spark Structured Streaming: poll, land, read, compact. Numbers from 1,115 tweets collected in 2026.
TL;DR
  • TwitterUtils is gone: spark-streaming-twitter left Spark for Apache Bahir, Bahir was retired in January 2024, and the Spark 4.3.0 docs call DStreams "a legacy project". Use Structured Streaming with a file or Kafka source.
  • The pattern: a Python poller calls /twitter/tweet/advanced_search with since_time:, trims each tweet to 14 fields, and atomically moves one JSON-lines file per non-empty poll into a directory that spark.readStream.json() watches.
  • Real volume is low: the "apache spark" OR pyspark search returned 158 tweets in 7 days (about 1 an hour, peak 5 in an hour); databricks returned 145 in 24 hours (peak 11 in an hour, 3 in a minute). Only a broad tag like #AI reached 171 in one hour.
  • Tiny files are the real problem: median landing file = 1 tweet for three of four streams. Parquet written per 60-second poll took 1,831 to 7,266 bytes per tweet vs 252 to 720 compacted (7x to 13x). Use maxFilesPerTrigger, hourly compaction, or trigger(availableNow=True) from cron.
  • Trim before Spark: the full API tweet object had a median of 4,800 to 5,365 bytes; the 14-field record 529 to 621 bytes, about 8x smaller, and still enough for windowed hashtag counts.
  • Cost: one query polled every 60 seconds is a $6.48 a month floor ($0.00015 per empty poll) plus $0.15 per 1,000 tweets returned, about 33x less per 1,000 tweets than the official X API's $0.005 per post read. See pricing.

This page is about the Spark half of a tweet pipeline in open-source Apache Spark: how tweets become a streaming DataFrame, how to window and de-duplicate them, and how to write them out without drowning in small files. It is not a firehose price comparison (for full-volume access and what it costs, see the Twitter firehose pricing comparison), and it does not cover the Kafka producer itself, which has its own Twitter Kafka producer guide. If you run Spark inside Databricks with Delta Live Tables and Auto Loader, the managed route is in our Databricks Twitter pipeline guide.

Search for "spark streaming twitter" and nearly every result is the same tutorial: add spark-streaming-twitter, call TwitterUtils.createStream(ssc, None), map the DStream to hashtags, reduceByKeyAndWindow, print. That code depended on a connector Spark no longer ships, a project that has since been retired, and X's old v1.1 streaming endpoint, while developer access to X data is now sold on a pay-per-usage rate card. Below is the version that works with Spark 4.3.0: a 90-line poller, a Structured Streaming job, a Kafka variant, a compaction job, and a DuckDB fallback for machines without Java.

We also measured what such a stream actually delivers. We collected 1,115 tweets in 2026 for four searches ("apache spark" OR pyspark over 7 days, databricks and #dataengineering over 24 hours, and a one-hour #AI lang:en burst) plus the latest posts of @ApacheSpark and @databricks, landed them exactly as the poller does, and measured files per day, tweets per file, bytes per tweet as JSON and Parquet, and the rows a 5-minute hashtag window produces. The study machine had no Java runtime, so the Spark job was not run there; the window logic was replayed in DuckDB, and the Spark code is written per the Spark 4.3.0 documentation.

Tweets in the median landing file for the "apache spark" OR pyspark search

1 tweet: the search returned 158 tweets in 7 days and 98.5% of 60-second polls were empty, so per-poll Parquet cost 7,266 bytes per tweet vs 720 compacted (1,115 tweets, collected in 2026).

01 — Section

Why the TwitterUtils tutorials stopped working

The connector left Spark. TwitterUtils lived in the spark-streaming-twitter module. Spark removed its Akka, MQTT, Twitter and ZeroMQ streaming connectors from the main project, and the code went to Apache Bahir, whose README says it started from connectors extracted from Spark just before that deletion. The last Bahir build documented for it is 2.3.4 (spark-streaming-twitter_2.11), compiled for Scala 2.11, while Spark 4.3.0 publishes Scala 2.13 artifacts.

The home of the connector is retired. The Apache Attic page for Bahir records that the project was retired in January 2024 and the move to the Attic completed in May 2024. Nobody is shipping a Twitter receiver for current Spark.

DStreams are legacy. The Spark Streaming programming guide for 4.3.0 opens with: "There are no longer updates to Spark Streaming and it's a legacy project." It points to Structured Streaming instead, which has no Twitter source at all; its built-in sources are files (text, CSV, JSON, ORC, Parquet), Kafka, and the socket and rate sources the docs mark for testing.

The upstream changed too. The receiver read X's v1.1 streaming endpoint through Twitter4J with app credentials. Developer access to X data today runs on the pay-per-usage rate card on docs.x.com ($0.005 per post read, capped at 3 million post reads a month before Enterprise). So a working pipeline needs two things the old tutorials skipped: a tweet source you can call today, and a hand-off Spark can read with exactly-once semantics.

Then (2015-2019 tutorials)Now (Spark 4.3.0)
TwitterUtils.createStream receiver, a DStreama poller you own, plus a file or Kafka source
StreamingContext and batch durationspark.readStream plus trigger(processingTime=...) or availableNow
reduceByKeyAndWindow on processing timewindow() on the tweet's own created_at, with withWatermark
print to consoleParquet or Delta sink with a checkpoint, exactly-once
02 — Section

The architecture: poller, landing zone, Structured Streaming, Parquet

1. Poller. A Python script asks the X search endpoint for tweets newer than its last run: /twitter/tweet/advanced_search with query="apache spark" OR pyspark since_time:<unix> and queryType=Latest. It follows next_cursor while has_next_page is true, re-reads a 120-second overlap so tweets indexed a little late are not missed, and drops IDs it already landed. No X developer account is needed; the request carries an X-API-Key header.

2. Landing zone. Each non-empty poll becomes one JSON-lines file. The Spark docs require that files "must be atomically placed in the given directory", which on one filesystem means writing to a temp folder and renaming, which is what os.replace does in the poller. On S3 or GCS, write the object in one PUT under the watched prefix (see the Twitter API to S3 guide).

3. Structured Streaming. spark.readStream.schema(schema).json("landing/tweets") treats new files as new rows. You parse created_at into an event-time column, add withWatermark("event_time", "10 minutes"), drop duplicates on id, explode hashtags and group by window(event_time, "5 minutes").

4. Sink. The file sink supports append output only and is exactly-once with a checkpointLocation. With a watermark, append mode writes each 5-minute window once it closes. Downstream, the counts are plain Parquet, readable from pandas, DuckDB or a warehouse; our pandas guide picks up from there.

Kafka instead of files is the same picture with a topic in the middle: the poller produces one record per tweet keyed by ID, and Spark reads it with .format("kafka"). Choose it when several consumers need the same tweets or you already run Kafka; choose files when Spark is the only reader and you want nothing else to operate.

03 — Section

Step 1: a poller that lands one JSON-lines file per poll

The full poller is at the end of this page. It makes three choices that matter for Spark.

Trim the record before Spark sees it. In our sample the full API tweet object had a median of 4,800 to 5,365 bytes of JSON depending on the query, mostly nested author, entities, card and quoted-tweet data. The 14 fields the hashtag job needs (id, created_at, stream, lang, text, author ID and follower count, five engagement counts, is_reply, hashtags) came to a median of 529 to 621 bytes, about 8x smaller. Keep the full object in a cold raw bucket if you need it later; give the stream the trimmed one.

Convert the timestamp. createdAt arrives as Sat Dec 05 21:31:26 +0000 2026, not ISO 8601. The poller converts it to ISO 8601 UTC (YYYY-MM-DDTHH:MM:SSZ) so Spark's to_timestamp parses it without a custom pattern.

Write nothing on an empty poll. The majority of polls find nothing (see the study), and an empty file still costs Spark a listing and a batch. The poller writes only when at least one new tweet came back.

Reading costs on twitterapi.io are per tweet returned: 15 credits ($0.00015) each, with a 15-credit minimum per request, so an empty poll costs $0.00015 and a full 20-tweet page $0.003. One query every 60 seconds is 43,200 polls a month, a $6.48 floor before tweets. Every 5 minutes it is $1.30. If searches return HTTP 503 or 429, the poller waits 60 seconds and retries the same page.

04 — Section

Step 2: the PySpark Structured Streaming job (windowed hashtag counts)

The job below reads the landing directory, de-duplicates, counts hashtags per 5-minute window and writes Parquet. Each option is taken from the Spark 4.3.0 Structured Streaming guide.

Declare the schema. The job declares the poller's 14 fields explicitly instead of letting Spark guess from whatever files happen to exist at start-up. That is also your contract: if the poller adds a field, add it here.

maxFilesPerTrigger caps how many new files one micro-batch reads (default: no maximum). With the tiny files measured below, 500 per trigger keeps a restart after downtime from building one enormous first batch. maxBytesPerTrigger is the alternative; the docs say the two cannot be set together. latestFirst processes newest files first when there is a backlog, and maxFileAge (default one week) ignores older files after the first batch.

Watermark and de-duplication. withWatermark("event_time", "10 minutes") tells Spark to keep window state until the maximum event time seen minus 10 minutes passes the window end; later rows for that window are dropped. It must be applied with append or update output; complete mode keeps all state. dropDuplicates(["id", "event_time"]) after the watermark removes tweets the poller re-read in its overlap while keeping de-duplication state bounded.

Trigger. processingTime="1 minute" starts a micro-batch every minute when there is new data; per the docs, if no new data is available no micro-batch is kicked off. For a low-volume stream like the Spark keyword, trigger(availableNow=True) run from cron every hour is often better: it processes everything available in as many batches as maxFilesPerTrigger allows, advances the watermark, and stops, so no cluster idles. trigger(once=True) is deprecated in favor of it.

Install note. pip install pyspark gives you local mode, but it needs a Java runtime on the machine. We could not run it on the study machine for that reason, so the code here follows the docs; the DuckDB block after it reproduces the same window counts and is what we ran.

python
# hashtag_stream.py - Spark Structured Streaming job over the landing directory.
#   pip install pyspark            (needs a Java runtime on the machine)
#   python hashtag_stream.py
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
from pyspark.sql.types import (ArrayType, BooleanType, LongType, StringType,
                               StructField, StructType)

spark = SparkSession.builder.appName("x-hashtag-stream").getOrCreate()

# A streaming file source needs an explicit schema: the poller's 14 trimmed fields.
schema = StructType([
    StructField("id", StringType()), StructField("created_at", StringType()),
    StructField("stream", StringType()), StructField("lang", StringType()),
    StructField("text", StringType()), StructField("author_id", StringType()),
    StructField("author_followers", LongType()), StructField("like_count", LongType()),
    StructField("retweet_count", LongType()), StructField("reply_count", LongType()),
    StructField("quote_count", LongType()), StructField("view_count", LongType()),
    StructField("is_reply", BooleanType()), StructField("hashtags", ArrayType(StringType())),
])

tweets = (spark.readStream
          .schema(schema)
          .option("maxFilesPerTrigger", 500)      # many tiny files: cap the files per micro-batch
          .json("landing/tweets")
          .withColumn("event_time", F.to_timestamp("created_at")))

# Event-time window: tolerate tweets up to 10 minutes late, drop re-read ids
deduped = (tweets.withWatermark("event_time", "10 minutes")
                 .dropDuplicates(["id", "event_time"]))

counts = (deduped
          .select("stream", "event_time", F.explode("hashtags").alias("tag"))
          .groupBy(F.window("event_time", "5 minutes"), "stream", "tag")
          .count()
          .select(F.col("window.start").alias("window_start"),
                  F.col("window.end").alias("window_end"), "stream", "tag", "count"))

# File sink supports append only; with a watermark, each window is written once it closes.
query = (counts.writeStream
         .format("parquet")
         .outputMode("append")
         .option("path", "lake/hashtag_counts")
         .option("checkpointLocation", "lake/_checkpoints/hashtag_counts")
         .trigger(processingTime="1 minute")      # or .trigger(availableNow=True) from cron
         .start())
query.awaitTermination()
05 — Section

Kafka source, compaction, and a DuckDB fallback

Kafka source. Add the connector with --packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.3.0. The source delivers key and value as binary plus topic, partition, offset, timestamp and timestampType, so you cast value to string and from_json it with the same schema. startingOffsets defaults to latest for streaming queries, which skips tweets produced before the first start; set earliest once, and later restarts resume from the checkpoint regardless. Use Kafka's timestamp only for lag monitoring; windows should use the tweet's own created_at.

Compaction. The study below shows why per-poll Parquet is wasteful: each file carries its own footer and schema, so a 1-tweet file costs several kilobytes. Two fixes work with open-source Spark: run the streaming job with an hourly availableNow trigger so each run writes fewer, larger files, or run a separate hourly batch job that rewrites the raw landing files as one Parquet file per day partition. The source option cleanSource="archive" (or "delete") moves processed files out of the landing directory so listings stay fast.

No Java? For a stream of a few hundred tweets a day, DuckDB reads the same landing files with one SQL statement, and time_bucket(INTERVAL 5 MINUTE, ts) produces the same windows as Spark's window(event_time, "5 minutes"). That is the replay we ran for the numbers on this page.

python
# Same job with a Kafka topic as the source (see the Kafka producer guide for the producer).
#   spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.13:4.3.0 hashtag_kafka.py
raw = (spark.readStream
       .format("kafka")
       .option("kafka.bootstrap.servers", "localhost:9092")
       .option("subscribe", "tweets")
       .option("startingOffsets", "earliest")   # default for streaming is "latest"
       .load())

tweets = (raw.select(F.from_json(F.col("value").cast("string"), schema).alias("t"))
             .select("t.*")
             .withColumn("event_time", F.to_timestamp("created_at")))
# ... then the same withWatermark / dropDuplicates / window / writeStream as above


# compact.py - once an hour, rewrite the last hour of tiny raw files as one Parquet file.
# Run it as a batch job (cron), not inside the streaming query.
from pyspark.sql import SparkSession
from pyspark.sql import functions as F

spark = SparkSession.builder.appName("x-compact").getOrCreate()
hour = spark.read.schema(schema).json("landing/tweets")      # schema from hashtag_stream.py
(hour.withColumn("dt", F.substring("created_at", 1, 10))
     .dropDuplicates(["id"])
     .coalesce(1)
     .write.mode("append").partitionBy("dt").parquet("lake/tweets"))
# then move processed files aside, or set the source option cleanSource="archive"


# No Java? The same 5-minute hashtag window in DuckDB over the same landing files.
#   pip install duckdb
import duckdb

rows = duckdb.sql("""
    WITH t AS (
        SELECT CAST(created_at AS TIMESTAMP) AS ts, stream, unnest(hashtags) AS tag
        FROM read_json('landing/tweets/*.json', format = 'newline_delimited')
    )
    SELECT time_bucket(INTERVAL 5 MINUTE, ts) AS window_start, stream, tag, count(*) AS n
    FROM t
    GROUP BY ALL
    ORDER BY window_start DESC, n DESC
    LIMIT 20
""").fetchall()
for r in rows:
    print(r)
06 — Section

What the stream actually carries: four searches, 1,115 tweets

Spark tutorials assume a torrent. Topic searches are a trickle. We landed each search's tweets as the poller would, one file per non-empty 60-second or 5-minute poll, and measured the result.

StreamTweets in windowTweets per hour (mean, peak)Peak in one minuteEmpty 60 s polls
"apache spark" OR pyspark, 7 days1581.0, 5298.5%
databricks, 24 h1456.2, 11390.4%
#dataengineering, 24 h311.3, 3197.8%
#AI lang:en, 1 h burst171173, 113 in one clock hour2311.5%

The Spark keyword is quiet. 158 tweets in 7 days is about one an hour; the busiest hour held 5. @ApacheSpark itself posted 50 times across 191 days in its timeline (0.26 a day), while @databricks posted 60 times in 19 days (3.16 a day). A streaming job on this topic spends nearly all its time waiting.

Files are tiny. At a 60-second poll, the Spark search produced about 22 files a day with a median of 1 tweet and 0.64 KB each; databricks produced 138 files a day, also with a median of 1 tweet. Moving to 5-minute polls barely changed the file count for the quiet streams (21 and 109 a day) because tweets rarely arrive within 5 minutes of each other. Only the #AI burst produced multi-tweet files: a median of 3 per 60-second file and 12 per 5-minute file, about 1,311 files a day at the 60-second rate.

Hashtags. 41.1% of the Spark-search tweets carried at least one hashtag (118 distinct; #apachespark, #bigdata and #python lead), against 24.8% for databricks. The 5-minute window count for the Spark search emitted 345 (window, tag) rows across 63 windows in 7 days; the one-hour #AI burst emitted 388 rows in 13 windows with 300 distinct hashtags. That is the output a sink receives, and it is small.

Horizontal log-scale bar chart of non-empty landing files per day at 60-second and 5-minute polls. apache spark OR pyspark: 22 and 21 files a day, median 1 tweet, 98.5% and 92.6% of polls empty. databricks: 138 and 109, median 1 tweet, 90.4% and 62.2% empty. #dataengineering: 32 and 30, median 1 tweet, 97.8% and 89.6% empty. #AI lang:en burst: 1,311 and 316 files a day, median 3 and 12 tweets, 11.5% and 0% empty.
Landing files per day by poll interval. Three of four streams produce files with a median of one tweet. Collected in 2026.
07 — Section

Bytes per tweet: JSON, trimmed JSON, and the small-file Parquet penalty

We wrote each stream's trimmed records to Parquet twice with pyarrow (snappy compression): once as one file per 60-second poll, the way a naive streaming sink with a short trigger behaves on a trickle, and once compacted into a single file.

StreamFull API JSON (median bytes)Trimmed JSON line (median)Parquet, one file per 60 s pollParquet, compacted
"apache spark" OR pyspark5,1686217,266 per tweet720 per tweet
databricks4,9866066,429 per tweet521 per tweet
#dataengineering4,8006005,567 per tweet431 per tweet
#AI lang:en burst5,3655291,831 per tweet252 per tweet

Per-poll Parquet costs 7x to 13x. A Parquet file has a fixed footer and schema overhead of a few kilobytes, so when each file holds one tweet that overhead is the whole bill: 7,266 bytes per tweet for the Spark search, more than the full untrimmed JSON. Compacted, the same records take 720 bytes. The busier #AI stream amortizes better (1,831 vs 252) but is still 7.3x worse per poll.

What to do with it. Bytes are cheap at this volume; what hurts is file count. Thousands of 6 KB files a week slow every listing and every downstream read. Run the stream on an hourly availableNow trigger, compact raw files daily, or land into Kafka and let Spark write larger batches. The compacted footprint for a year of the Spark search at this rate is about 6 MB.

Grouped log-scale bar chart of bytes per tweet for four searches. apache spark OR pyspark: full JSON 5,168, Parquet per 60-second file 7,266, trimmed JSON 621, compacted Parquet 720. databricks: 4,986, 6,429, 606, 521. #dataengineering: 4,800, 5,567, 600, 431. #AI lang:en burst: 5,365, 1,831, 529, 252.
Bytes per tweet by storage layout. Per-poll Parquet files cost 7x to 13x a compacted file. Collected in 2026.
08 — Section

What it costs: twitterapi.io vs the official X API

Spark itself is free; the cost is reading tweets. On twitterapi.io, tweet endpoints bill 15 credits per tweet returned ($0.15 per 1,000), with a 15-credit minimum per request ($0.00015), and $1 = 100,000 credits. The official X API pay-per-usage rate card on docs.x.com is $0.005 per post read and $0.010 per user read, capped at 3 million post reads a month, which is about 33x more per 1,000 tweets ($5 vs $0.15).

Feed (one query)Polls a monthTweets a monthtwitterapi.io a monthOfficial X API reads a month
"apache spark" OR pyspark, every 60 s43,200about 680about $6.48 floor + $0.10 = $6.58680 x $0.005 = $3.40, plus a paid developer account
the same, every 5 min8,640about 680about $1.30 + $0.10 = $1.40$3.40
databricks, every 60 s43,200about 4,350about $6.48 + $0.65 = $7.13about $21.75
#AI lang:en, every 60 s43,200about 124,000about $18.70 (tweets exceed the floor)about $620

Tweets a month are the study's rates times 30 days. On a quiet query the polling floor dominates; the X API row there assumes every call returns only new posts. On a busy query, per-tweet price dominates and the 33x ratio shows. Read limits: accounts that have never paid are limited to 0.2 requests a second, 20 once paid, which leaves ample headroom for a few queries a minute. Plans and starter credits are on the pricing page; new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days).

09 — Section

How we collected this

Question: what does a tweet stream look like to Spark Structured Streaming when tweets are landed as one JSON-lines file per poll: tweets per hour and minute, files per day and tweets per file at 60-second and 5-minute polls, bytes per tweet as full JSON, trimmed JSON and Parquet, and the rows a 5-minute hashtag window emits.

Queries and accounts: /twitter/tweet/advanced_search with queryType=Latest for "apache spark" OR pyspark (7 days), databricks (24 hours), #dataengineering (24 hours) and #AI lang:en (one hour), bounded with since_time: and until_time:; plus /twitter/user/last_tweets for @ApacheSpark and @databricks, 3 pages each. 65 successful requests, 1,115 tweets, about $0.17 in reads, collected in 2026. Searches that returned HTTP 503 were retried after a pause and are not charged.

Method: tweets were trimmed to the poller's 14 fields, bucketed by createdAt into 60-second and 300-second files under a temp directory, and measured. Parquet sizes come from pyarrow 21.0.0 with snappy compression. The 5-minute window count was replayed in DuckDB 1.4.5 with time_bucket. No Java runtime was available, so PySpark was not run; we report no Spark latency or throughput numbers.

What the sample cannot show: search returns what X indexes for the query, which may be fewer posts than were published; the #AI stream covers one hour, so its daily figures are extrapolations. Files were bucketed by creation time, so indexing delay, which decides the watermark you need, is not measured; 10 minutes is a conservative choice, not a measured one. Volumes change with news and product launches.

Aggregates only. Raw search pages, which are mostly posts by private individuals, stayed on the collection machine and were deleted; the committed sample has no IDs, handles, URLs or text. Only organization accounts are named.

python
"""land_tweets.py - poll X (Twitter) search and land each poll as one JSON-lines file
that Spark Structured Streaming's file source can read.

    pip install requests
    export TWITTERAPI_IO_API_KEY=...
    python land_tweets.py --loop 60          # one file per non-empty poll, every 60 s

Cost: an empty poll costs the $0.00015 minimum (15 credits); each tweet returned costs
$0.00015. One query every 60 s is a $6.48 a month floor.
"""
import argparse
import json
import os
import time
from datetime import datetime, timezone

import requests

API = "https://api.twitterapi.io"
KEY = os.environ["TWITTERAPI_IO_API_KEY"]
QUERIES = {                      # stream name -> X search query
    "spark": '"apache spark" OR pyspark',
    "databricks": "databricks",
}
LANDING = "landing/tweets"       # Spark reads this directory
TMP = "landing/_tmp"             # files are written here, then moved in atomically
STATE = "landing/_state.json"
OVERLAP = 120                    # seconds re-read each poll; ids already landed are dropped
MAX_PAGES = 10                   # safety cap per poll (20 tweets per page)


def created_iso(s):
    # createdAt looks like "Sat Dec 05 21:31:26 +0000 2026", not ISO 8601
    return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y").astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def trim(t, stream):
    """14 fields: about 600 bytes a line instead of about 5,000 for the full object."""
    a = t.get("author") or {}
    ent = t.get("entities") or {}
    return {
        "id": t["id"], "created_at": created_iso(t["createdAt"]), "stream": stream,
        "lang": t.get("lang"), "text": t.get("text") or "",
        "author_id": a.get("id"), "author_followers": a.get("followers"),
        "like_count": t.get("likeCount"), "retweet_count": t.get("retweetCount"),
        "reply_count": t.get("replyCount"), "quote_count": t.get("quoteCount"),
        "view_count": t.get("viewCount"), "is_reply": bool(t.get("isReply")),
        "hashtags": [h.get("text", "").lower() for h in (ent.get("hashtags") or [])],
    }


def search(query, since_time):
    tweets, cursor = [], None
    for _ in range(MAX_PAGES):
        params = {"query": f"{query} since_time:{since_time}", "queryType": "Latest"}
        if cursor:
            params["cursor"] = cursor
        r = requests.get(f"{API}/twitter/tweet/advanced_search",
                         headers={"X-API-Key": KEY}, params=params, timeout=30)
        if r.status_code in (429, 503):          # back off, keep the cursor state
            time.sleep(60)
            continue
        r.raise_for_status()
        body = r.json()
        page = body.get("tweets") or []
        tweets.extend(page)
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
    return tweets


def poll_once(state):
    os.makedirs(LANDING, exist_ok=True)
    os.makedirs(TMP, exist_ok=True)
    started = int(time.time())
    for stream, query in QUERIES.items():
        since = state.get(stream, started - 3600) - OVERLAP
        seen = set(state.get(f"{stream}_seen", []))
        rows = [trim(t, stream) for t in search(query, since) if t["id"] not in seen]
        if rows:                                  # an empty poll writes no file
            name = f"{stream}-{started}.json"
            with open(f"{TMP}/{name}", "w") as f:
                f.write("\n".join(json.dumps(r) for r in rows) + "\n")
            os.replace(f"{TMP}/{name}", f"{LANDING}/{name}")   # atomic move on one filesystem
        state[stream] = started
        state[f"{stream}_seen"] = (list(seen) + [r["id"] for r in rows])[-5000:]
        print(f"{stream}: {len(rows)} new tweet(s)")
    with open(STATE, "w") as f:
        json.dump(state, f)


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("--loop", type=int, help="poll every N seconds")
    args = ap.parse_args()
    state = json.load(open(STATE)) if os.path.exists(STATE) else {}
    while True:
        poll_once(state)
        if not args.loop:
            break
        time.sleep(args.loop)

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

10 — Questions

Questions readers ask

Does TwitterUtils still work with Spark?

No. TwitterUtils came from the spark-streaming-twitter module, which Spark removed and Apache Bahir took over; the last documented Bahir build is 2.3.4 for Scala 2.11, and Bahir was retired in January 2024. It also read X's old v1.1 streaming endpoint. Use Structured Streaming with a file or Kafka source fed by a poller.

Is Spark Streaming (DStreams) deprecated?

The Spark 4.3.0 docs describe it as legacy: there are no longer updates to Spark Streaming, and new applications should use Structured Streaming. Structured Streaming has no Twitter source, so tweets come in through files, Kafka, or another supported source.

How do I stream tweets into PySpark?

Run a poller that calls /twitter/tweet/advanced_search with a since_time: cursor every 60 seconds or 5 minutes, trim each tweet, and atomically move one JSON-lines file per non-empty poll into a directory. Then spark.readStream.schema(schema).json(directory), add withWatermark on created_at, window and count, and write Parquet with a checkpointLocation.

Files or Kafka between X and Spark?

Files if Spark is the only consumer and you want nothing else to run; Kafka if several systems read the same tweets or you already operate a cluster. Spark reads Kafka with the spark-sql-kafka-0-10_2.13 package; note startingOffsets defaults to latest for streaming queries.

Why are my Spark output files so small?

Because tweet streams on a topic are a trickle. In our sample the median landing file held 1 tweet for three of four searches, and one Parquet file per 60-second poll cost 7x to 13x the bytes per tweet of a compacted file. Use an hourly availableNow trigger, maxFilesPerTrigger, or a daily compaction job.

What watermark should I use for tweets?

Long enough to cover your poll interval plus the overlap you re-read and any search indexing delay. With a 60-second poll and a 120-second overlap, 10 minutes is a conservative start. Remember a watermark only works with append or update output; the file sink is append only.

Can I run this without Java?

PySpark needs a Java runtime. For a few hundred tweets a day, DuckDB or pandas reads the same JSON-lines files, and DuckDB's time_bucket gives the same 5-minute windows as Spark's window(). Move to Spark when volume or the rest of your platform calls for it.

How much does a Spark tweet stream cost to feed?

On twitterapi.io, one query polled every 60 seconds costs a $6.48 a month floor ($0.00015 per empty poll) plus $0.15 per 1,000 tweets returned; every 5 minutes the floor is $1.30. The official X API charges $0.005 per post read, about 33x more per 1,000 tweets.

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.