Twitter (X) API + Apache Airflow: A Daily Tweet DAG You Can Backfill

By TwitterAPI.io Team•13 min read
Diagram of a daily Twitter (X) Airflow DAG: window from logical_date, extract task paging advanced_search, load task upserting by tweet id with an Asset outlet, warehouse and downstream DAGs
A daily tweet-search DAG on Airflow 3.4.0; the run log on this page was collected in 2026.
TL;DR
  • Shape: @daily DAG, extract (HttpHook GET to /twitter/tweet/advanced_search, one UTC day via since_time/until_time, follow next_cursor) then load (upsert by tweet id, outlets=[Asset]).
  • Airflow 3 imports: from airflow.sdk import dag, task, Asset, get_current_context; Dataset is now Asset; execution_date is gone from the context, use logical_date.
  • Gotcha we hit: with schedule="@daily", every run reported data_interval_start == data_interval_end. Compute start = logical_date - 1 day yourself or use CronDataIntervalTimetable.
  • Real run: 7 partitions, 1,553 tweets (154 to 292 per day), 87 requests, median extract 42 s, one task-level retry that Airflow absorbed.
  • Idempotency check: re-running a partition returned 182 of the 191 original ids (9 were gone) and inserted 0 new rows.
  • Cost: $0.23 for the whole backfill on TwitterAPI.io vs $7.77 at the official X API rate of $0.005 per post read.

This page is about orchestration: how to schedule, partition, retry and backfill tweet extraction in Apache Airflow. If you already know you want a warehouse and only need the load step, the Twitter API to BigQuery guide covers the BigQuery side in depth, and the AWS Lambda version covers a serverless job with no scheduler of its own. Here the warehouse is a detail; the DAG is the point.

Search for a Twitter Airflow tutorial and the results are mostly written for an older world: Airflow 2 imports such as airflow.decorators, Tweepy with a bearer token on X API access tiers that have since changed, and DAGs that fetch "the last N tweets" with no window, so a retry or a backfill duplicates or skips data. None of them show what a real backfill does run by run.

So we built the DAG on Apache Airflow 3.4.0 (the current release on PyPI), ran it for seven daily partitions of one search, re-ran one partition to test idempotency, and kept the run log. The numbers below come from that run, collected in 2026; the code you can copy is the same structure with Airflow's own HttpHook doing the HTTP calls.

Real Airflow 3 backfill, 7 daily partitions of one tweet search

1,553 tweets in 87 requests for $0.23, 0 duplicate ids, 1 task retry absorbed, collected in 2026

01 — Section

What a Twitter Airflow DAG needs to do

A tweet pipeline in Airflow is an ordinary extract-and-load DAG with three properties that are easy to get wrong with social data: the window must be fixed, the load must be idempotent, and the extract must survive a bad page without losing the partition.

One run, one window. Each DAG run owns a fixed time range, here one UTC day. The query is the same every day; only since_time: and until_time: change. A run for a given day always asks for the same tweets, which is what makes retries and backfills safe.

Pages until the API says stop. /twitter/tweet/advanced_search returns up to 20 tweets per page plus has_next_page and next_cursor. The loop follows the cursor and stops when has_next_page is false, with a hard page cap so a runaway query cannot drain credits.

Upsert, never append. The load writes with INSERT ... ON CONFLICT(id) DO UPDATE (SQLite, PostgreSQL) or MERGE ... ON tweet_id (BigQuery, Snowflake, Databricks). A retried task, a manual re-run and an overlapping backfill all land on the same rows. Engagement counts update in place, which is usually what you want.

Small XCom, big files. The extract task writes its rows to a staging file and returns the path. Airflow's XCom is for metadata, not for a thousand tweet objects.

Tell the rest of the platform. The load task declares outlets=[Asset(...)]. Any DAG scheduled on that Asset starts after a successful load, so the report, the sentiment model or the dbt run waits for data instead of a clock. The consumer side is a few lines, shown below; the producer DAG is the full example at the end of the page.

python
from airflow.sdk import Asset, dag, task

TWEETS = Asset("sqlite:///opt/airflow/data/tweets.db/tweets")   # same URI as the producer


@dag(schedule=[TWEETS], catchup=False, tags=["twitter"])
def twitter_daily_report():
    @task
    def summarize() -> None:
        import sqlite3
        con = sqlite3.connect("/opt/airflow/data/tweets.db")
        n, likes = con.execute("SELECT COUNT(*), SUM(like_count) FROM tweets").fetchone()
        print(f"{n} tweets stored, {likes} likes in total")

    summarize()


twitter_daily_report()
02 — Section

Airflow 3 changed the imports: get them right first

Airflow 3 moved DAG authoring to the Task SDK. The upgrade guide on airflow.apache.org maps the old paths to the new ones, and the old ones are deprecated. If you copy a Twitter DAG from an older tutorial, these are the lines to change.

Airflow 2Airflow 3
from airflow.decorators import dag, taskfrom airflow.sdk import dag, task
from airflow.models.dag import DAGfrom airflow.sdk import DAG
from airflow.datasets import Datasetfrom airflow.sdk import Asset
context["execution_date"]context["logical_date"]
airflow dags backfill ...airflow backfill create --dag-id ...

Catchup is off by default. The upgrade guide says catchup_by_default is now False, so a new DAG with an old start_date will not silently schedule hundreds of runs. History is something you ask for with a backfill.

Tasks no longer talk to the metadata database. Direct metadata DB access from task code is restricted in Airflow 3. That does not matter for this DAG (it only needs a Connection, which the hook reads through the SDK), but it rules out old patterns that queried DagRun from inside a task to find the previous watermark. The window from logical_date replaces that.

What we ran. pip install apache-airflow==3.4.0 apache-airflow-providers-http into a Python 3.12 virtualenv (PyPI lists >=3.11 as the requirement for this release). The DAG on this page parses cleanly in that install with zero import errors, and HttpHook built https://api.twitterapi.io/twitter/tweet/advanced_search from the Connection with the X-API-Key header attached.

03 — Section

The "@daily" data interval trap (we hit it)

In every one of our 7 runs, the task context reported data_interval_start equal to data_interval_end. That is not a bug in the DAG. In Airflow 3 a bare cron string such as "@daily" is scheduled with CronTriggerTimetable, which fires at a point in time and carries a zero-length interval. Parsing the DAG confirms it: the timetable prints as CronTriggerTimetable(expression='0 0 * * *', ..., interval=datetime.timedelta(0)).

A DAG that builds its search window as since_time:{data_interval_start} and until_time:{data_interval_end} would therefore ask X for a window of zero seconds and load nothing, every day, without failing. A DAG ported from Airflow 2 is exposed to exactly this, because Airflow 2 gave a bare cron string a real one-day data interval; the upgrade guide lists a create_cron_data_intervals setting that only affects DAGs passing a bare cron string to schedule=.

Two fixes. Keep "@daily" and derive the window from logical_date (the run at midnight loads the day that just ended), or pass CronDataIntervalTimetable explicitly and read the interval from the context. The study used the first; the snippet below shows both.

The run for a day happens after the day. Whichever you choose, schedule the run at or after the end of its window. Our seventh partition was extracted shortly before its UTC day closed: its newest tweet was 40 minutes before the window end. A run that fires early silently misses the tail of the day; re-running it later with --reprocess-behavior completed fills the gap because the load is an upsert.

python
# Option A (used on this page): keep "@daily" and compute the window yourself
end = ctx["logical_date"]
start = end - timedelta(days=1)

# Option B: ask for real data intervals, then read them from the context
from airflow.sdk import CronDataIntervalTimetable

@dag(schedule=CronDataIntervalTimetable("0 0 * * *", timezone="UTC"), ...)
def twitter_search_daily(): ...
# inside a task: ctx["data_interval_start"], ctx["data_interval_end"]
04 — Section

We ran the DAG with dag.test() once per logical date for seven consecutive UTC days, then ran the first day a second time. The query was airflow lang:en -filter:retweets with queryType=Latest, capped at 20 pages per partition (no partition came close). Each run is one row below.

PartitionTweetsRequestsExtract timeCost
P11911125 s$0.029
P2154920 s$0.023
P32921643 s$0.044
P42601461 s$0.039
P52371449 s$0.036
P62191239 s$0.033
P72001142 s$0.030
Total1,55387median 42 s$0.234

Volume varied by almost 2x day to day. The quietest partition returned 154 tweets and the busiest 292, with a median of 219. A fixed page cap sized on a quiet day would truncate a busy one, which is why the cap here is a safety stop, not a sampling rule.

Every partition ended on an empty page. The last full page of each day still said has_next_page: true, and the next request returned zero tweets. That happened 7 times in 87 requests. Each empty page is billed at the 15-credit minimum ($0.00015), so the full backfill spent 105 credits ($0.00105) learning that a day was finished. Budget one extra request per partition.

Pages are not always 20. 13 of 87 pages carried fewer than 20 tweets (the 7 empty ones included). The API reference says pages can come back short because non-tweet items are filtered out, so never use len(tweets) < 20 as the stop condition; use has_next_page.

The window held. 0 of 1,553 tweets had a createdAt outside their partition's [since_time, until_time) range, 0 ids repeated within a partition and 0 appeared in two partitions. Adjacent windows that share a boundary second did not double-count anything.

python
# What the study measured inside the extract task (abridged from analyze.py).
# Every page is timed; the window check and the id set run after the loop.
pages, t0 = [], time.time()
for _ in range(MAX_PAGES):
    p0 = time.time()
    body = fetch_page(hook, params)
    pages.append({"n": len(body.get("tweets") or []), "secs": time.time() - p0})
    cursor = body.get("next_cursor")
    if not body.get("has_next_page") or not cursor:
        break
    params["cursor"] = cursor
extract_secs = time.time() - t0

# credits per request: 15 per tweet returned, 15 minimum per request
credits = sum(max(15, 15 * p["n"]) for p in pages)
usd = credits / 100_000
Bar chart of seven daily Airflow partitions: tweets per partition from 154 to 292, with API requests and extract wall time inside each bar; partition 3 needed one task retry
Tweets, requests and extract time per partition, Airflow 3.4.0, collected in 2026.
05 — Section

Retries: what actually failed, and who caught it

One extract try failed. In partition P3 a single search page failed five HTTP attempts in a row; the client gave up and the task exited with an error. Airflow marked the task up_for_retry, waited the configured retry_delay, and the second try paged the whole day again and succeeded with 292 tweets in 16 requests. The other six partitions finished on the first try with zero HTTP retries (87 attempts for 87 successful requests across the backfill, counting final tries).

That is the two-layer design working as intended. The inner layer, inside fetch_page, retries HTTP 429 and 5xx with a fixed exponential backoff of 1, 2, 4, 8 and 16 seconds, which absorbs a short blip without involving the scheduler. The outer layer is Airflow's retries=3 on the task, which absorbs a longer outage.

A task retry starts the partition from page one. The TaskFlow tutorial notes that each retry reruns the function from the start. Pages fetched before the failure are fetched again and billed again, which is acceptable for a day-sized partition (P3 is about $0.04) and a reason not to make partitions a month wide. The upsert makes the duplicate pages harmless for the data.

Do not retry 4xx other than 429. A 400 means the query or a parameter is wrong; retrying it five times and then three more times at the task level just repeats the error. fetch_page raises immediately on anything that is not 200, 429 or 5xx.

Rate limits and parallel backfills. TwitterAPI.io allows 0.2 requests per second before the first payment and 20 once paid (50 on Scale, 500 on Business). max_active_runs=3 on a backfill means three extract tasks paging at once; that is far under 20 requests per second, but on an unpaid key it would hit 429s immediately. Match --max-active-runs to your limit, or put the extract tasks in an Airflow pool with a slot count that fits.

For a broader treatment of 429 handling outside Airflow, see how to handle a Twitter API rate limit.

06 — Section

Is the load really idempotent? We re-ran a partition

After the seven-day backfill we ran partition P1 again, the way airflow backfill create --reprocess-behavior completed or a manual clear would. The second run made 11 requests and returned 182 tweets.

CheckFirst runRe-run
Tweet ids returned191182
Ids in both runs182182
Ids only in this run90
Rows inserted by the upsert1910

Zero new rows, zero duplicates. The upsert matched every re-fetched id to an existing row and only refreshed its counts. That is the property that lets you clear and re-run any day in the Airflow UI without thinking about it.

But a re-run does not delete. 9 tweets that the first run loaded did not come back the second time, probably deleted or made unavailable in between. An upsert keeps them. If your use case must reflect deletions (compliance, a public dashboard), make the load a partition swap instead: delete the day's rows and insert the fresh set in one transaction, or keep a last_seen_run column and filter on it.

Search results move slightly over time. Treat a backfilled day as a snapshot taken at extract time, not as an exact replay of what was posted. Engagement counts in particular keep growing for days after a tweet is posted; re-running recent partitions later is a reasonable way to refresh them.

07 — Section

What the backfill cost, against the official X API

TwitterAPI.io bills 15 credits per tweet returned with a 15-credit minimum per request, and $1 buys 100,000 credits, so $0.15 per 1,000 tweets. The official X API pay-per-use rate card on docs.x.com/x-api/getting-started/pricing lists $0.005 per post read, capped at 3 million post reads a month on pay-per-use plans, with Enterprise above that.

For the same 1,553 tweets, the backfill cost $0.23 on TwitterAPI.io (including the seven empty last pages) and would cost $7.77 at the X API post-read rate, about 33x per 1,000 tweets. The re-run of P1 added 2,745 credits ($0.0274).

Scale it to your query. Cost tracks the number of tweets your query matches per day, not the number of DAG runs. A daily partition of 200 tweets is about $0.03 a day, about $0.90 a month. A query that matches 20,000 tweets a day is $3 a day. The Twitter rate limit calculator helps size request rates; current prices and plans 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); see the pricing page for the amount. Purchased credits never expire.

Grouped bar chart of cost per daily partition: TwitterAPI.io between $0.023 and $0.044, official X API post-read rate between $0.77 and $1.46 for the same tweets
Cost per partition at both published rate cards for the same 1,553 tweets, collected in 2026.
08 — Section

Backfill, test and wire downstream DAGs

Airflow 3 replaced airflow dags backfill with airflow backfill create, which asks the scheduler to create one DAG run per schedule interval in the range. The backfill docs list the flags; --from-date and --to-date are inclusive, --reprocess-behavior chooses between missing runs only (none, the default), missing and failed (failed) or everything (completed), and --max-active-runs caps concurrency for the backfill independently of the DAG's own setting.

Test one day before you backfill a month. airflow dags test <dag_id> <date> runs a single DAG run in-process with no scheduler, which is how the study ran each partition. Check the row count and the window before scaling up.

Backfill does not apply to unscheduled DAGs. The docs say backfill does not make sense for DAGs without a time-based schedule, so keep the extract DAG on a cron or timetable even if you also trigger it manually.

Downstream on data, not on time. A second DAG with schedule=[TWEETS] runs after each successful load of the producer, per the Asset scheduling docs. That is the clean place for a summary, a model or a dbt job; it never runs on an empty day that failed.

bash
# one-time setup
export AIRFLOW_CONN_TWITTERAPI='{"conn_type": "http", "host": "https://api.twitterapi.io", "extra": {"X-API-Key": "YOUR_KEY"}}'

# check the DAG parses and the task list is right
airflow dags list-import-errors
airflow tasks list twitter_search_daily

# one partition, in-process, no scheduler needed
airflow dags test twitter_search_daily YYYY-MM-DD

# a week of history: one run per day, three at a time, failed days reprocessed
airflow backfill create --dag-id twitter_search_daily \
    --from-date YYYY-MM-DD --to-date YYYY-MM-DD \
    --max-active-runs 3 --reprocess-behavior failed

# preview which runs a backfill would create, without running them
airflow backfill create --dag-id twitter_search_daily \
    --from-date YYYY-MM-DD --to-date YYYY-MM-DD --dry-run
09 — Section

How we collected this

Question. What does a real Airflow 3 backfill of a tweet-search DAG look like partition by partition: tweets, requests, retries, wall time, window accuracy, duplicates, cost, and whether a re-run is idempotent?

Setup. Apache Airflow 3.4.0 with apache-airflow-providers-http in a throwaway Python 3.12 virtualenv on one laptop, SQLite as both the metadata database and the target table. The DAG had the same two tasks, schedule, window logic and upsert as the snippet on this page; each partition ran through dag.test(). The one difference: the extract task paged the API through our internal rate-limited read client instead of HttpHook, because several jobs share one request budget; the requests, parameters and pagination were identical.

Query and window. airflow lang:en -filter:retweets, queryType=Latest, seven consecutive UTC days, each one partition, plus one re-run of the first. Collected in 2026.

Sample. 1,553 tweets, 98 requests including the re-run.

What it cannot show. Wall times include queueing behind a shared 5 requests per second client used by other jobs at the same time, so the median page time of about 2 to 4 seconds is an upper bound, not the API's latency. One query on one week is not a forecast for yours. The keyword airflow is noisy: only 10% of the matched tweets mentioned a data-engineering term (DAG, pipeline, ETL, Python and similar), and the rest did not mention any of those terms. That is why the copyable DAG searches the phrase "apache airflow" instead. No write calls were made.

Privacy. Search authors are private individuals, so only aggregates and de-identified per-tweet rows (partition, hour, lengths, counts, flags) are kept; no tweet ids, text, handles or author ids were committed.

python
"""twitter_search_daily.py - Apache Airflow 3 DAG: one UTC day of X (Twitter) search per run.

pip install "apache-airflow==3.4.0" apache-airflow-providers-http
Connection (env var, or Admin > Connections in the UI):
  AIRFLOW_CONN_TWITTERAPI='{"conn_type": "http", "host": "https://api.twitterapi.io",
                            "extra": {"X-API-Key": "YOUR_KEY"}}'
Backfill a week:
  airflow backfill create --dag-id twitter_search_daily --from-date YYYY-MM-DD --to-date YYYY-MM-DD
"""
import json
import sqlite3
import time
from datetime import datetime, timedelta, timezone

from airflow.providers.http.hooks.http import HttpHook
from airflow.sdk import Asset, dag, get_current_context, task

QUERY = '"apache airflow" lang:en -filter:retweets'
MAX_PAGES = 50                      # hard stop per partition (50 x 20 = 1,000 tweets)
DB_PATH = "/opt/airflow/data/tweets.db"
TWEETS = Asset("sqlite:///opt/airflow/data/tweets.db/tweets")


def fetch_page(hook: HttpHook, params: dict) -> dict:
    """One search page. Retries 429 and 5xx with a fixed backoff; raises on anything else."""
    for attempt in range(5):
        resp = hook.run(
            endpoint="/twitter/tweet/advanced_search",
            data=params,                              # GET: sent as query parameters
            extra_options={"check_response": False, "timeout": 40},
        )
        if resp.status_code == 200:
            return resp.json()
        if resp.status_code in (429, 500, 502, 503, 504):
            time.sleep(2 ** attempt)                  # 1, 2, 4, 8, 16 s
            continue
        raise RuntimeError(f"HTTP {resp.status_code}: {resp.text[:200]}")
    raise RuntimeError("advanced_search kept failing; let Airflow retry the task")


@dag(
    schedule="@daily",
    start_date=datetime(2026, 1, 1, tzinfo=timezone.utc),
    catchup=False,
    max_active_runs=3,
    tags=["twitter", "x-api"],
)
def twitter_search_daily():
    @task(retries=3, retry_delay=timedelta(minutes=2))
    def extract() -> str:
        ctx = get_current_context()
        # "@daily" is a bare cron string, so Airflow 3 uses CronTriggerTimetable:
        # data_interval_start == data_interval_end == logical_date. Load the day before it.
        end = ctx["logical_date"]
        start = end - timedelta(days=1)
        since, until = int(start.timestamp()), int(end.timestamp())
        hook = HttpHook(method="GET", http_conn_id="twitterapi")
        params = {"query": f"{QUERY} since_time:{since} until_time:{until}", "queryType": "Latest"}
        rows = []
        for _ in range(MAX_PAGES):
            body = fetch_page(hook, params)
            for t in body.get("tweets") or []:
                author = t.get("author") or {}
                rows.append({
                    "id": t["id"],
                    "created_at": t["createdAt"],
                    "text": t.get("text", ""),
                    "lang": t.get("lang"),
                    "author_id": author.get("id"),
                    "author_username": author.get("userName"),
                    "like_count": t.get("likeCount", 0),
                    "retweet_count": t.get("retweetCount", 0),
                    "reply_count": t.get("replyCount", 0),
                    "view_count": t.get("viewCount", 0),
                })
            cursor = body.get("next_cursor")
            if not body.get("has_next_page") or not cursor:
                break
            params["cursor"] = cursor
        path = f"/opt/airflow/data/staging/tweets_{start:%Y%m%d}.json"   # one file per partition
        with open(path, "w") as f:
            json.dump(rows, f)
        return path                                   # pass the path, not the rows, through XCom

    @task(outlets=[TWEETS])
    def load(path: str) -> int:
        rows = json.load(open(path))
        con = sqlite3.connect(DB_PATH)
        con.execute("""CREATE TABLE IF NOT EXISTS tweets (
            id TEXT PRIMARY KEY, created_at TEXT, text TEXT, lang TEXT,
            author_id TEXT, author_username TEXT, like_count INT, retweet_count INT,
            reply_count INT, view_count INT)""")
        con.executemany("""INSERT INTO tweets VALUES
            (:id, :created_at, :text, :lang, :author_id, :author_username,
             :like_count, :retweet_count, :reply_count, :view_count)
            ON CONFLICT(id) DO UPDATE SET like_count = excluded.like_count,
              retweet_count = excluded.retweet_count, reply_count = excluded.reply_count,
              view_count = excluded.view_count""", rows)
        con.commit()
        con.close()
        return len(rows)

    load(extract())


twitter_search_daily()

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

10 — Questions

Questions readers ask

Can Apache Airflow pull tweets from Twitter (X)?

Yes. Airflow does not ship a Twitter operator, so a DAG calls an X data API over HTTP, usually with the HTTP provider's HttpHook inside a TaskFlow task. The pattern on this page pages /twitter/tweet/advanced_search for one UTC day per run and upserts the rows by tweet id.

Is there an Airflow Twitter provider or operator?

There is no maintained Twitter or X provider in the Apache Airflow provider list. The Hive provider's docs still contain an old example DAG named for Twitter, but its fetch step is a placeholder. Use apache-airflow-providers-http and a Connection holding your API key.

Why does my Twitter DAG load zero tweets in Airflow 3?

If the window comes from data_interval_start and data_interval_end and the schedule is a cron string such as "@daily", Airflow 3 uses CronTriggerTimetable, which has a zero-length interval. Every run asks for zero seconds of tweets. Compute the window from logical_date, or schedule with CronDataIntervalTimetable.

How do I backfill historical tweets with Airflow?

Give the DAG a time-based schedule and a window per run, then run airflow backfill create --dag-id <id> --from-date <first day> --to-date <last day>. Airflow creates one run per day. --max-active-runs limits how many run at once; keep it within your API rate limit.

How do I avoid duplicate tweets when a task retries?

Make the load an upsert keyed by the tweet id: INSERT ... ON CONFLICT(id) DO UPDATE in SQLite or PostgreSQL, MERGE in BigQuery, Snowflake or Databricks. In our re-run test the upsert inserted 0 new rows for a partition that was already loaded.

Should I pass tweets between tasks with XCom?

Pass a reference, not the data. Write the rows to a staging file or object storage path in extract and return the path; load reads it. XCom is stored in the metadata database and is meant for small values.

How much does a daily Twitter Airflow DAG cost to run?

API cost depends on how many tweets the query matches. Our test search matched 154 to 292 tweets a day and cost about $0.02 to $0.04 per day on TwitterAPI.io at $0.15 per 1,000 tweets, versus $0.005 per post read on the official X API pay-per-use plan. Airflow itself is free and open source; hosting it is your cost.

What schedule should a tweet DAG use?

Daily partitions suit reporting and warehousing. For near-real-time alerts, a scheduler is the wrong tool; use a push mechanism such as a webhook or stream and let Airflow handle the batch side.

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.