Twitter (X) API on Azure: Timer-Triggered Functions to Event Hubs

- Pattern: timer trigger (NCRONTAB
0 */1 * * * *) -> Azure Function ->/twitter/tweet/advanced_searchwithsince_time-> dedup -> Event Hubs output binding -> Stream Analytics / Power BI. - Empty checks dominate: in our local run, 74% of 34 search requests returned zero posts; the niche queries found 0 and 1 new posts across their runs.
- Overlap costs duplicates: a 120 s overlap meant 48% of returned posts were re-reads (16 of 33). They are billed, so keep the overlap short and dedup by
id. - Skip the empty follow-up page: 9 requests (16% of credits) were second pages that returned nothing after a short first page still reported
has_next_page. - Cost at 15 credits per post: $0.15 per 1,000 posts, $0.00015 for an empty check; a 60 s schedule's floor is $6.48 a month, a 5 min schedule's is $1.30. The official X API lists $0.005 per post read (about 33x more per 1,000).
- Azure facts per Microsoft docs: the timer trigger does not retry failed runs, runs on one instance only, Consumption is legacy (use Flex Consumption), and Linux Consumption retires 30 September 2028.
This page is about running a Twitter (X) ingestion job inside Azure: Azure Functions for the schedule, Event Hubs for the stream, Key Vault for the key. If you are on AWS, the same pattern with EventBridge and Lambda is in Twitter API with AWS Lambda; if you only need dashboards, Twitter API to Power BI skips the streaming layer and loads posts straight into a report.
X does not push public search results to Azure on its own, so an Azure pipeline for live posts is a poller: something wakes up on a schedule, asks for what is new since the last run, and forwards it. Azure Functions' timer trigger is the natural host for that, and the parts that decide whether the pipeline is cheap and correct are small: the checkpoint, the overlap window, the dedup set, and when to stop paginating.
We ran the polling loop locally against the live API on three queries and measured what each run actually sees. The numbers below come from that run; every Azure behavior is quoted from Microsoft's documentation, because we did not deploy anything to Azure.
74%
The architecture: five pieces, one schedule
Timer trigger. An NCRONTAB expression with six fields ({second} {minute} {hour} {day} {month} {day-of-week}). 0 */1 * * * * runs every minute and 0 */5 * * * * every five. The default time zone is UTC. Per the docs, if the app scales out "only a single instance of a timer-triggered function is run across all instances", and it will not fire again while an invocation is still running.
The function. A Python v2 function (decorators, no function.json) that calls /twitter/tweet/advanced_search with queryType=Latest and a since_time:<unix> operator inside the query, follows next_cursor, and drops IDs it has already seen.
State. The checkpoint (the start time of the last successful run) and a bounded set of recent IDs. A small JSON blob in the storage account the host already uses (AzureWebJobsStorage) is enough; Table storage or Cosmos DB work too.
Event Hubs. The function's output binding (@app.event_hub_output) publishes the new posts as a batch. Downstream consumers (Stream Analytics, a second function, Fabric, or Capture to storage) read independently through consumer groups.
Key Vault. The TwitterAPI.io key is stored as a secret and exposed to the function as an app setting whose value is @Microsoft.KeyVault(VaultName=myvault;SecretName=twitterapi-io-key). The function's managed identity needs the Key Vault Secrets User role. Your code reads a normal environment variable.
The function code (Python v2 model)
The function below is the whole ingestion step. It reads the checkpoint, subtracts a 120-second overlap so posts indexed slightly late are not lost, pages through the search, filters by id, publishes the new posts to Event Hubs, and only then advances the checkpoint. If the API call raises, the function fails before saving state, so the next run covers the same window again. That matters because, per the timer trigger docs, "the timer trigger doesn't retry after a function fails".
The response shape is the one in our docs: posts are in the top-level tweets[] array, with has_next_page and next_cursor alongside. Each post carries id, createdAt, text, lang, the engagement counts (likeCount, retweetCount, replyCount, quoteCount, viewCount) and an author object with userName and followers.
The page-stop rule is deliberate: a page with fewer than 20 posts is treated as the last page. In our run, a short first page still reported has_next_page as true, and following it returned an empty page each time; see the study section for what that cost.
import json
import logging
import os
from typing import List
import azure.functions as func
import requests
from azure.storage.blob import BlobClient
app = func.FunctionApp()
BASE = "https://api.twitterapi.io"
API_KEY = os.environ["TWITTERAPI_IO_KEY"] # app setting holding a Key Vault reference
QUERY = os.environ.get("X_QUERY", "azure lang:en")
OVERLAP_S = 120 # re-read the last 2 minutes to catch late-indexed posts
MAX_PAGES = 5
def state_blob() -> BlobClient:
return BlobClient.from_connection_string(
os.environ["AzureWebJobsStorage"], container_name="x-poller", blob_name="state.json")
def load_state() -> dict:
try:
return json.loads(state_blob().download_blob().readall())
except Exception:
return {"checkpoint": None, "seen": []}
@app.timer_trigger(schedule="0 */1 * * * *", arg_name="timer", run_on_startup=False)
@app.event_hub_output(arg_name="events", event_hub_name="x-posts", connection="EventHubConnection")
def poll_x(timer: func.TimerRequest, events: func.Out[List[str]]) -> None:
import time
run_start = int(time.time())
state = load_state()
since = (state["checkpoint"] - OVERLAP_S) if state["checkpoint"] else run_start - 300
seen = set(state["seen"])
params = {"query": f"{QUERY} since_time:{since}", "queryType": "Latest"}
out = []
for _ in range(MAX_PAGES):
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
headers={"X-API-Key": API_KEY}, params=params, timeout=30)
r.raise_for_status() # a failed run leaves the checkpoint where it was
body = r.json()
tweets = body.get("tweets") or []
for t in tweets:
if t["id"] in seen:
continue
seen.add(t["id"])
out.append(json.dumps({
"id": t["id"], "createdAt": t["createdAt"], "text": t["text"],
"lang": t.get("lang"), "likeCount": t.get("likeCount"),
"author": t["author"]["userName"]}))
if len(tweets) < 20 or not body.get("has_next_page") or not body.get("next_cursor"):
break # a short page is the last page: skip the empty follow-up call
params["cursor"] = body["next_cursor"]
if out:
events.set(out)
state = {"checkpoint": run_start, "seen": list(seen)[-5000:]}
state_blob().upload_blob(json.dumps(state), overwrite=True)
logging.info("poll_x: %d new posts, since=%d", len(out), since)
host.json, settings and Key Vault
Event Hubs bindings come from the extension bundle declared in host.json; the timer binding needs no package. For local runs with Azure Functions Core Tools, put the settings in local.settings.json under Values; in Azure, set them as app settings and make the API key a Key Vault reference.
Two Key Vault details from Microsoft's docs are worth knowing before you rotate the key. If the reference has no secret version, the app picks up a new version "within 24 hours" because App Service caches resolved references and refetches them every 24 hours; any configuration change restarts the app and refetches immediately. And if a reference cannot be resolved, the literal @Microsoft.KeyVault(...) string is passed to your code instead, so an authentication error from the API right after deployment usually means the identity or role assignment is missing, not that the key is wrong.
Set functionTimeout explicitly. Per the hosting docs, the default is 30 minutes on Flex Consumption, Premium and Dedicated and 5 minutes (maximum 10) on the legacy Consumption plan. A poller that pages up to five times at a few seconds per request finishes far inside either limit.
{
"version": "2.0",
"functionTimeout": "00:05:00",
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[4.*, 5.0.0)"
}
}
# local.settings.json (Values) for Core Tools; in Azure, set the key as a Key Vault reference:
# TWITTERAPI_IO_KEY = @Microsoft.KeyVault(VaultName=myvault;SecretName=twitterapi-io-key)
# EventHubConnection = <Event Hubs namespace connection string or identity-based settings>
# AzureWebJobsStorage = <storage account used by the host, also holds state.json>What we measured: the polling loop on three queries
We ran the same loop as the function above, as a local Python process, against the live API: 9 runs per query at a 60-second spacing, a 120-second overlap, a 300-second look-back on the first run and up to 5 pages per run. Three queries spanned the volume range an Azure team would plausibly watch: azure lang:en (broad), "power bi" lang:en (product) and ("azure functions" OR "event hubs" OR "azure openai") lang:en (niche).
Empty is the normal case. 25 of 34 successful requests (74%) returned zero posts. The product query found nothing in eight minutes; a separate single Latest page for the same query held 20 posts spread over 5.01 hours, about 4.0 an hour, so a 60-second schedule on that query is paying the minimum almost every time.
Freshness. For the broad query, the median post was 85 seconds old when a run first saw it and the p90 was 229 seconds, which includes the up-to-60-second wait for the next run.
Late arrivals. The overlap window caught 0 posts that were older than the previous checkpoint but unseen. In this short run the overlap only produced duplicates; it is insurance, and a longer run is needed to price it properly.
Failures. The first run of Q1 and Q2 failed after the client's own retries during a wave of HTTP 503 responses from the search endpoint (a 503 is not billed). Because the checkpoint was not advanced, the next Q1 run looked back further and picked up 9 posts, the largest batch of the session.

Latency and what it means for the timer
Over 32 requests that succeeded on the first attempt, latency from our machine was 3815 ms at the median, 5511 ms at p95 and 6733 ms at worst (minimum 1374 ms). Searches are slower than single-object lookups because the search is executed upstream at request time.
For a timer function, the practical consequence is the page cap. Five pages at the p95 latency is under 30 seconds, comfortably inside a 60-second schedule, so one run finishes before the next is due and the single-instance rule never has to skip an occurrence. If a query regularly fills five pages per minute, either shorten the schedule or split the query; do not raise the cap until the run starts to overlap the next one.
We did not measure cold starts: the loop ran in a warm local process. Microsoft's hosting docs say Flex Consumption has "improved cold start even when scaled to zero" and supports always-ready instances, and the Premium plan keeps instances warm. With a one-minute schedule, a Flex Consumption app is unlikely to sit idle long enough to go cold, but that is per the docs, not something we timed.
What it costs: API, then Azure
TwitterAPI.io bills search by posts returned: 15 credits per post, $0.15 per 1,000 posts, with a 15-credit minimum per request. An empty check costs $0.00015 and a full 20-post page $0.003. Duplicates from the overlap are returned again and therefore billed again, which is the reason to keep the overlap short.
The per-1,000 figure ($0.512) is higher than the list $0.15 because of the empty checks, the trailing pages and the overlap re-reads; on a busy query with full pages it approaches $0.15 plus whatever the overlap adds. The Q1 monthly figure extrapolates a few minutes of late-night weekend traffic, so treat it as an order of magnitude.
For comparison, the official X API pricing page (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 a month. Per 1,000 posts that is $5 against $0.15, about 33x. Reading public posts through TwitterAPI.io needs no X account; see pricing for credits and the free starter credits (no card, one per person or network, expiring after 31 days).
The Azure side is billed separately by Microsoft: Functions executions and memory on Flex Consumption, Event Hubs throughput units and ingress, storage transactions. A one-minute poller is small for all three, but check the Azure pricing pages for your region rather than trusting a number here.
Event Hubs and the downstream
Per the Event Hubs quotas page, a single publication can be up to 256 KB on Basic and 1 MB on Standard and Premium, and the limit applies to a batch as a whole. A post serialized as compact JSON with text and a few fields is well under a kilobyte, so even a five-page run (100 posts) fits in one Standard batch.
Retention is 1 day on Basic and 7 days on Standard. Basic allows one consumer group per event hub and Standard 20, which matters as soon as two consumers read the same stream (say Stream Analytics for a live tile and a second function that writes to a database). Standard also offers Capture to storage, priced separately.
From Event Hubs, Stream Analytics can window the posts (counts per minute, mentions per keyword) and push the result to Power BI or a SQL table. If what you need is a daily report rather than a live tile, skip Event Hubs and land the posts directly in storage or a database; Twitter API to Power BI shows that shorter path, and Twitter API with Kafka covers the same pattern on a self-managed log.
Design choices that change correctness or cost
Checkpoint after publishing, not before. If you save the checkpoint first and the Event Hubs write fails, those posts are gone. Saving last means a crash replays the window and the dedup set absorbs the repeats.
Bound the seen set. The overlap only reaches back a couple of minutes, so a few thousand recent IDs is plenty; keeping every ID forever makes the state blob grow without limit.
Dedup downstream too. Event Hubs delivers at least once to consumers, and a function that fails after publishing but before saving state will publish the same posts again on the next run. Use the post id as the key in whatever store sits at the end.
One query per function, or one function with a list. The timer's single-instance rule applies per function, so three queries in one function run in sequence. That is fine at a minute; at shorter schedules, split them.
Never run_on_startup in production. Microsoft's docs warn it runs the function whenever the app scales or restarts, at unpredictable times, which for a poller means extra billed checks.
When polling is the wrong tool. If you watch specific accounts rather than a keyword, a server-side filter rule that pushes matches to a webhook (an HTTP-triggered function) removes the empty checks entirely; see the webhooks setup guide and the rate limit calculator to size either approach.
How we collected this
Question. What does a timer-triggered poller with a since checkpoint see per run: posts per run, overlap duplicates, empty runs, latency and cost per 1,000 new posts?
Queries. azure lang:en, "power bi" lang:en, and ("azure functions" OR "event hubs" OR "azure openai") lang:en, queryType=Latest.
Method and window. A local Python loop using our rate-limited study client: 9 runs per query, 60 s apart, 120 s overlap, up to 5 pages per run, one continuous session of about nine minutes, collected in 2026. 34 successful requests and 2 that failed after retries. Plus one extra Latest page for the product query to estimate its posting rate.
What was not run. No Azure resources were created: Azure Functions, Event Hubs, Key Vault, Stream Analytics and Power BI behavior is described per Microsoft's documentation. Cold start was not measured. The session ran late on a weekend night (UTC), so volumes are low and are not a forecast for any other hour; a 24-hour run would give a much better per-month estimate.
Privacy. Search results contain posts by private individuals. Raw pages stayed on the collecting machine and are not published; the study files hold per-run counts and latencies only (no post IDs, text, URLs or handles).
# Local dry run of the same loop without Azure: prints what each run would publish.
import time
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": "YOUR_API_KEY"}
QUERY = "azure lang:en"
checkpoint, seen = None, set()
for run in range(5):
run_start = int(time.time())
since = (checkpoint - 120) if checkpoint else run_start - 300
params = {"query": f"{QUERY} since_time:{since}", "queryType": "Latest"}
new = dup = 0
while True:
body = requests.get(f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS, params=params, timeout=30).json()
tweets = body.get("tweets") or []
for t in tweets:
if t["id"] in seen:
dup += 1
else:
seen.add(t["id"]); new += 1
if len(tweets) < 20 or not body.get("has_next_page"):
break
params["cursor"] = body["next_cursor"]
checkpoint = run_start
print(f"run {run}: {new} new, {dup} duplicates dropped")
time.sleep(60) # fixed pacing, same as the timer schedule
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Can Azure receive Twitter (X) posts without polling?
Not for public search results on its own: X does not push them to an Azure endpoint. Either poll on a schedule with a timer-triggered function, as on this page, or use a filter rule that pushes matching posts to a webhook you host, which in Azure is an HTTP-triggered function.
Which Azure Functions plan should a Twitter poller use?
Per Microsoft's hosting docs, the Consumption plan is now legacy and Linux Consumption retires on 30 September 2028; new serverless apps should use Flex Consumption. A one-minute poller is a light workload, so Flex Consumption is a reasonable default; Premium makes sense only if you already run other always-warm functions.
How often should the timer run?
As often as the freshness you need, not more. Every empty check still costs the $0.00015 minimum: $6.48 a month at 60 s and $1.30 at 5 min per query. In our run, 74% of checks came back empty, so low-volume queries are good candidates for a 5-minute schedule.
Why does my timer function sometimes skip a run?
Per the timer trigger docs, a timer function runs on a single instance and does not fire again while an invocation is still running, and a failed run is not retried. If runs take longer than the interval, lower the page cap or lengthen the schedule; store the checkpoint so the next run covers what was missed.
How do I keep the API key out of code?
Store it in Key Vault and set the app setting to a Key Vault reference such as @Microsoft.KeyVault(VaultName=myvault;SecretName=twitterapi-io-key). Give the function app's managed identity the Key Vault Secrets User role. A new secret version is picked up within 24 hours, or immediately after any configuration change.
How do I avoid duplicate posts in Event Hubs?
Dedup by post id before publishing, keep the overlap window short, and save the checkpoint only after the publish succeeds. In our run, a 120 s overlap made 48% of returned posts duplicates. Consumers should still treat id as the key, because Event Hubs delivery is at least once.
How much does the official X API charge for the same data?
The X API pricing page lists $0.005 per post read and $0.010 per user read on pay-per-usage, capped at 3 million post reads a month. TwitterAPI.io charges $0.15 per 1,000 posts returned, about 33x less per 1,000 posts.
Continue
- Microsoft Learn: Timer trigger for Azure Functions
- Microsoft Learn: Event Hubs output binding for Azure Functions
- Microsoft Learn: Azure Functions hosting options and limits
- Microsoft Learn: Key Vault references as app settings
- Microsoft Learn: Event Hubs quotas and limits
- X API pricing (docs.x.com)
- X API guides and endpoints
- Twitter API with AWS Lambda and EventBridge
- Twitter API to Power BI dashboards
- Twitter API streaming into Kafka
- Twitter API on Cloudflare Workers cron
- Twitter API cursor pagination
- TwitterAPI.io pricing and credits
- 01Twitter (X) Fake News Detection: Datasets, Features and Code
- 02Twitter (X) Topic Modeling in Python: BERTopic vs LDA on Real Tweets
- 03How to Make a Twitter (X) Word Cloud from Tweets in Python
- 04Twitter (X) Hate Speech Detection in Python: Models, Thresholds and a Real Reply Study
- 05Spark Streaming Twitter (X) Data in 2026: PySpark Structured Streaming Without TwitterUtils
- 06Twitter (X) API to Excel: Power Query, Python and CSV, Tested on 1,361 Posts
- 07PhantomBuster Pricing: Plans, Execution Hours and What X (Twitter) Data Really Costs
- 08Composio Pricing in 2026: Plans, Tool Calls and the Twitter (X) Data Bill
Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.
Stop reading. Start building.
Starter credits cover real testing on real data. Google sign-in, no card, no application queue.
Get an API keyAlready building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.