Twitter (X) Data in Grafana: Mention Dashboards and Spike Alerts

- Two wiring options. The Infinity data source queries the API live from Grafana; a Python poller into PostgreSQL keeps history for trend panels and alert rules.
- Infinity config that matters: API Key auth with Key
X-API-Key, Inheader, plushttps://api.twitterapi.ioin Allowed hosts (required once auth is set). Use the JSONata or JQ backend parser if you want alerting. - Real series: 835 posts matching 'grafana' over 336 hours, collected in 2026. Mean 2.49 per hour, median 2, p95 7, max 9; 65 hours had zero posts.
- The baseline moved: 35.9 posts a day in week one, 83.4 in week two. A fixed threshold set in week one would have fired all through week two.
- Alert tested: mean + 3 sd over the trailing 168 hours fired in 1 of 168 hours (9 posts vs a threshold of 8.15); with a floor of 10 posts it fired 0 times. The same SQL replayed in DuckDB gave the same answer.
- Cost: an hourly refresh at this volume is about $0.27 a month; a once-a-minute check is up to about $6.75, almost all of it the $0.00015 minimum on empty checks.
This guide is about Grafana, the operations dashboard: panels that refresh on a timer and alert rules that page someone when a number crosses a line. That is a different job from our Streamlit hashtag dashboard, which is a Python app you write yourself, and from the Power BI connection, which is a scheduled business report. Grafana fits when X data sits next to your service metrics and you want a mention spike to land in the same on-call channel as an error spike.
Everything here was checked against Grafana's own documentation this session (the Infinity plugin pages and the alerting fundamentals) and our API reference at docs.twitterapi.io. We could not run a Grafana server for this page, so there is no Grafana screenshot. Instead we pulled a real 14-day mention series, charted it the way a time-series panel would draw it, and replayed the alert rule's SQL over every hour to count how often it would have fired.
The short version: use Infinity for a live table or stat panel, use a poller plus PostgreSQL for anything with history, and never alert on a fixed number for social volume, because the level moves week to week.
1 of 168 hours for the keyword 'grafana' (835 posts over 14 days, collected in 2026); 0 with a 10-post floor. The series averaged 2.49 posts an hour and 19.3% of hours were empty.
Which wiring to choose: Infinity live queries or a poller with a database
Grafana does not store data. Every panel is a query against a data source at render time, so the real question is where the X data lives when the panel asks for it.
Why history matters here. At the 2.49 posts an hour we measured for 'grafana', one 20-post page reaches back about 8.0 hours, and only about 5.8 hours in the busier second week. A 7-day panel built on a live query would silently show the last few hours and nothing before. Bigger brands shrink that window to minutes.
Why calls matter. An Infinity panel re-runs its query on every refresh in every open browser, and an Infinity-backed alert rule runs it on every evaluation. Each request costs at least 15 credits ($0.00015). A poller decouples cost from how many people watch the dashboard.
Option A: the Infinity data source, configured for TwitterAPI.io
Install the plugin with grafana cli plugins install yesoreyeram-infinity-datasource, or on Docker pass -e "GF_INSTALL_PLUGINS=yesoreyeram-infinity-datasource". Grafana's installation page lists Grafana 11.6 or later as the requirement.
Authentication. In the data source settings choose API Key. Per the Infinity authentication docs, Key "becomes the key of the header or query parameter", Value is the token, and In picks header or query. Use Key X-API-Key, In header. The key is stored in the data source, not in each panel, so dashboard viewers never see it.
Allowed hosts. The same page says the Allowed hosts list is required once authentication, custom headers or TLS certificates are configured. Add https://api.twitterapi.io; without it the data source refuses to send your key anywhere.
The query. Type JSON, Source URL, Method GET, Parser JSONata. Add query and queryType under "Headers, Request params". Rows/Root tweets turns the response's tweet array into rows; add Columns with a Selector, Title and Type for each field. Pick Format Table for a table panel. The tweet fields you get back are the ones in our docs: createdAt, text, lang, likeCount, retweetCount, replyCount, viewCount, url and an author object.
Parser choice is an alerting choice. Grafana's Infinity docs say alerting, shared dashboards, recorded queries and query caching are only available with a backend parser (JSONata or JQ). The older frontend parsers render panels but cannot back an alert rule.
Data source: Infinity (plugin id yesoreyeram-infinity-datasource, Grafana 11.6 or later)
Authentication: API Key
Key: X-API-Key
Value: <your TwitterAPI.io key>
In: header
Allowed hosts: https://api.twitterapi.io
Panel 1, Table "latest mentions"
Type: JSON Parser: JSONata (backend) Source: URL Method: GET
URL: https://api.twitterapi.io/twitter/tweet/advanced_search
Request params: query = grafana queryType = Latest
Rows/Root: tweets
Columns: createdAt (String), lang (String), likeCount (Number),
viewCount (Number), url (String)
Panel 2, Stat "followers"
URL: https://api.twitterapi.io/twitter/user/info
Request params: userName = grafana
Rows/Root: data
Columns: followers (Number), statusesCount (Number)Option B: a poller that writes every mention into PostgreSQL
For a time series you need every post, not the newest page. The poller below runs once a minute, asks /twitter/tweet/advanced_search for grafana since_time:<last seen> until_time:<now>, follows next_cursor while has_next_page is true, and inserts rows with ON CONFLICT (id) DO NOTHING so a 5-minute overlap never double counts. The full script is at the end of this page.
Why since_time and not paging backward forever. Our API docs list since_time:UNIX_SECONDS and until_time:UNIX_SECONDS as the window operators (date-style since: is not supported). While collecting this study, one open-ended 'grafana' search for the whole window stopped paginating after 240 posts, about 59.5 hours back, while day-sized windows returned everything. Bounded windows are the reliable way to backfill.
What to store. Keep id as the primary key, created_at as timestamptz, and only the fields a panel will use (lang, is_reply, like_count, view_count). Post text and handles are personal data you rarely need for a count; leave them out unless a table panel needs them.
Panel query. Add the PostgreSQL data source, then a time-series panel. Per Grafana's PostgreSQL query editor docs, $__timeFilter(column) expands to the dashboard's time range and $__timeGroupAlias buckets the time column and names it time, which is what the time-series format expects (a column named time, sorted by time).
-- Grafana panel query (PostgreSQL data source, Format: Time series)
SELECT
$__timeGroupAlias(created_at, '1h'),
count(*) AS mentions
FROM x_mentions
WHERE keyword = 'grafana'
AND $__timeFilter(created_at)
GROUP BY 1
ORDER BY 1What the panel shows: 14 days of 'grafana' mentions, hour by hour
We ran the Option B logic as a one-off backfill: 14 days, 336 whole UTC hours, every post the search returned for 'grafana', collected in 2026. That gave 835 posts from 589 distinct accounts. The chart below is our matplotlib rendering of those counts, drawn to look like a Grafana time-series panel. It is not a Grafana screenshot.
Read the shape before you set a threshold. The series is small integers with a long run of zeros: 19.3% of hours had no post at all. Counts that low make percentage-change alerts meaningless (one post to three is +200%), which is why the rule below uses standard deviations and a floor.
The level more than doubled. Week one averaged 35.9 posts a day, week two 83.4. We did not establish the cause; it could be news, a release cycle or a seasonal lull in week one. Either way a fixed line drawn from week one's data would have fired for days in week two.

The alert rule: mean + 3 standard deviations, tested hour by hour
Grafana-managed alert rules are built from queries plus expressions. Per Grafana's alerting docs, a Reduce expression turns a series into one number (Min, Max, Mean, Median, Sum, Count, Last), a Math expression works on $A-style references, and a Threshold expression returns 1 when its condition (Is above, Is below, Is equal to, Is within range) holds. Classic conditions still exist but the docs say they "should be avoided if possible".
The simplest robust design is to let SQL do the statistics and hand Grafana one number. Query A below returns excess: the last complete hour's count minus the trailing 168-hour mean + 3 sd, with empty hours counted as zero through generate_series. Expression B is a Threshold on A, Is above 0. Put the rule in an evaluation group that runs every few minutes; the result only changes once an hour.
How we tested it. We evaluated both rules on hours 169 to 336, each against the 168 hours before it. Rule A fired once: a Sunday 19:00 UTC hour with 9 posts against a threshold of 8.15. Over the evaluated week the threshold itself ranged from 6.79 to 10.36, because the trailing baseline absorbed the busier days. We then loaded the de-identified hour buckets into DuckDB 1.4.5 and ran the same SQL for each hour: it fired 1 time under rule A and 0 under rule B, matching the Python result. We did not run it on a PostgreSQL server; the functions used (generate_series, date_trunc, stddev_pop) are standard PostgreSQL.
Is one alert a week right? For a brand that sees about 59.6 posts a day, one alert in 168 hours is a quiet, useful rate. The floor matters more than the multiplier: rule B's 10-post minimum removed the single alert, which a person would probably have judged as noise (9 posts in an hour is above normal, not a crisis). Pick the floor from what your team would actually act on.
Pending period and keep firing for. Per Grafana's rule evaluation docs, a pending period holds an alert in Pending until the condition has lasted that long (zero skips Pending), and keep firing for holds it in Recovering after the condition clears to stop flapping. For hourly buckets a pending period of 0 and keep firing for of one hour is a sensible start.
Where it goes. Contact points hold the notification config; Grafana's list includes Slack, Email, Discord, Telegram, Microsoft Teams, PagerDuty and a generic Webhook. Route mention alerts to the channel where someone owns the response, not to the on-call pager.
-- Alert rule query A: returns ONE number, the excess over the threshold.
-- Last complete UTC hour vs mean + 3 sd of the 168 hours before it (empty hours count as 0).
WITH hours AS (
SELECT generate_series(
date_trunc('hour', now()) - interval '169 hours',
date_trunc('hour', now()) - interval '2 hours',
interval '1 hour') AS h
), base AS (
SELECT h,
(SELECT count(*) FROM x_mentions m
WHERE m.keyword = 'grafana'
AND m.created_at >= h AND m.created_at < h + interval '1 hour') AS n
FROM hours
), cur AS (
SELECT count(*) AS n FROM x_mentions
WHERE keyword = 'grafana'
AND created_at >= date_trunc('hour', now()) - interval '1 hour'
AND created_at < date_trunc('hour', now())
)
SELECT now() AS time,
CASE WHEN cur.n >= 10 -- rule B floor; drop this line for rule A
THEN cur.n - (avg(base.n) + 3 * stddev_pop(base.n))
ELSE -1 END AS excess
FROM base, cur
GROUP BY cur.n;
-- Expression B: Threshold, input A, Is above 0Daily rhythm and audience: what else belongs on the dashboard
Hour of day matters for staffing the response. Across all 14 days the busiest UTC hour was 13:00 and the quietest 02:00, so a spike at 02:00 UTC is more unusual than the same count at 13:00. If you see that pattern in your own data, a seasonal baseline (same hour of day over the past four weeks) is the next refinement after the flat 168-hour window.
Split panels by language. A third of the conversation was not English (12.3% Japanese, 7.1% Chinese in this sample). A lang column in the table lets you add a stacked panel or a per-language alert. Replies were 26.3% of posts and quotes 7.9%; the search returned no retweets.
Follower count as a stat panel. /twitter/user/info returns followers, statusesCount and more for a public account. The organization account @grafana had 73,836 followers when we collected this study. Poll it hourly into a followers table for a growth line, or use an Infinity stat panel for the current value.

What it costs: TwitterAPI.io vs the official X API for a Grafana feed
Tweet endpoints, including /twitter/tweet/advanced_search, cost 15 credits per post returned, which is $0.15 per 1,000 posts. Each request has a minimum of 15 credits ($0.00015), so a check that finds nothing still costs $0.00015. The official X API's pay-per-usage rate card at 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.
Read the minute row carefully. Almost all of the $6.75 is the minimum on empty checks: 43,200 checks a month at $0.00015 is $6.48 on its own. The X column counts only the posts read; we did not price empty requests there. For a series charted in hourly buckets, a check every 5 minutes (about $1.30 a month in minimums) gives the same panel.
Live Infinity panels multiply this. Every viewer's refresh is another request. A wall display refreshing every 30 seconds is 86,400 requests a month on its own; point it at the PostgreSQL table instead.
Our own study. The backfill used 63 requests and cost about $0.13. Paid accounts get 20 requests a second; before the first payment the limit is 0.2 a second, which still covers a once-a-minute poller. New accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days); see pricing for the amount.
How we collected this
Question. What does an hourly mention-rate series for one brand keyword look like, and how often would a simple spike alert fire on it?
Query. /twitter/tweet/advanced_search with query grafana, queryType Latest, in bounded since_time / until_time windows covering 336 whole UTC hours (14 days), plus one /twitter/user/info call for the public @grafana organization account. Collected in 2026.
Sample. 835 unique posts from 589 accounts, 63 requests in total (including two probe requests), about $0.13 at our rates.
Method. Posts bucketed into UTC hours. Rule A: an hour alerts when its count exceeds the mean + 3 population standard deviations of the previous 168 hours. Rule B adds a 10-post floor. Evaluated on the last 168 hours; replayed in DuckDB 1.4.5 with the page's SQL.
What it cannot show. One keyword over two weeks is one shape, not a law. The word 'grafana' also matches posts that are not about the company. Search results reflect what the search index returned at collection time; posts deleted earlier are absent. We did not measure Grafana's rendering or alert-delivery latency, and we did not run a Grafana or PostgreSQL server.
Privacy. Aggregates only. The posting accounts are private individuals, so raw pages were not kept in the repository and the published sample holds hour buckets and type flags with no ids, text or handles. The only named account is the @grafana organization.
Operating notes: keys, gaps, and when to move past Grafana
Keep the key server-side. With Infinity, the key lives in the data source config. With the poller, keep it in an environment variable on the host; Grafana then only holds database credentials.
Gaps are not zeros. If the poller stops, the panel shows a flat zero that looks like a quiet hour. Add a heartbeat row per run and a second alert rule on "no heartbeat in 10 minutes", or use the rule's No Data handling, which Grafana lets you customize.
Re-reads are free of double counts, not of cost. The 5-minute overlap re-reads a few posts per run. At low volume that is cents a month; at high volume shrink the overlap.
When you need push instead of poll. For sub-minute reaction to a keyword, a webhook filter rule beats a poller. Our keyword alerts guide and the monitoring via API guide cover that pattern; you can still write the pushed posts into the same PostgreSQL table so Grafana charts them unchanged.
import os
import time
from datetime import datetime, timezone
import psycopg
import requests
API_KEY = os.environ["TWITTERAPI_IO_KEY"]
DSN = os.environ["PG_DSN"] # postgresql://user:pass@host:5432/metrics
KEYWORD = "grafana"
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": API_KEY}
DDL = """
CREATE TABLE IF NOT EXISTS x_mentions (
id text PRIMARY KEY,
keyword text NOT NULL,
created_at timestamptz NOT NULL,
lang text,
is_reply boolean,
like_count integer,
view_count bigint
);
CREATE INDEX IF NOT EXISTS x_mentions_kw_time ON x_mentions (keyword, created_at);
"""
def parse_time(s):
# createdAt looks like "Thu Oct 16 12:34:56 +0000 2026"
return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
def fetch_since(since_unix, until_unix, max_pages=20):
"""Return every post matching KEYWORD between two unix times, following next_cursor."""
query = f"{KEYWORD} since_time:{since_unix} until_time:{until_unix}"
cursor, out = "", []
for _ in range(max_pages):
r = requests.get(
f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS,
params={"query": query, "queryType": "Latest", "cursor": cursor},
timeout=30,
)
r.raise_for_status()
body = r.json()
out.extend(body.get("tweets", []))
if not body.get("has_next_page"):
break
cursor = body.get("next_cursor", "")
return out
def store(conn, tweets):
rows = [
(t["id"], KEYWORD, parse_time(t["createdAt"]), t.get("lang"), bool(t.get("isReply")),
t.get("likeCount", 0), t.get("viewCount", 0))
for t in tweets
]
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO x_mentions (id, keyword, created_at, lang, is_reply, like_count, view_count) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (id) DO NOTHING",
rows,
)
conn.commit()
return len(rows)
def last_seen(conn):
with conn.cursor() as cur:
cur.execute("SELECT max(created_at) FROM x_mentions WHERE keyword = %s", (KEYWORD,))
ts = cur.fetchone()[0]
# first run: backfill one day; later runs: re-read a 5-minute overlap (ids de-duplicate)
return int(ts.timestamp()) - 300 if ts else int(time.time()) - 86400
def main():
with psycopg.connect(DSN) as conn:
conn.execute(DDL)
conn.commit()
while True:
now = int(time.time())
got = fetch_since(last_seen(conn), now)
print(datetime.now(timezone.utc).isoformat(timespec="seconds"), "stored", store(conn, got))
time.sleep(60) # fixed pacing: one check a minute
if __name__ == "__main__":
main()
Researching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
Is there an official Twitter (X) data source for Grafana?
Not one maintained for X data. The usual path is the Infinity data source, which per Grafana's docs queries JSON, CSV, TSV, XML and GraphQL endpoints, pointed at an X data API, or a poller that writes posts into a database Grafana already supports, such as PostgreSQL.
How do I pass the API key in the Infinity data source?
Choose API Key authentication, set Key to X-API-Key, Value to your key and In to header, then add https://api.twitterapi.io under Allowed hosts. Infinity's docs say Allowed hosts is required once authentication is configured.
Can Grafana alert directly on an Infinity query?
Yes, if the query uses a backend parser (JSONata or JQ). Grafana's Infinity docs list alerting among the features that need a backend parser. Each evaluation is an API request, so a rule evaluated every minute is 43,200 requests a month, at least $6.48 at the $0.00015 minimum.
Why not just chart the live search result as a time series?
One page holds up to 20 posts. At the 2.49 posts an hour we measured for 'grafana', that reaches back about 8.0 hours, so a 7-day panel would be almost empty. Store posts in PostgreSQL and group by hour instead.
What threshold should a mention spike alert use?
A rolling baseline, not a fixed number. On 14 days of 'grafana' mentions, mean + 3 standard deviations over the trailing 168 hours fired in 1 of 168 hours, and a 10-post floor removed even that one. The daily level more than doubled between the two weeks, which would have broken any fixed line.
Does this need an X developer account?
No. Reads through TwitterAPI.io use your TwitterAPI.io key in the X-API-Key header; no X account or X developer app is involved.
How much does a Grafana Twitter dashboard cost to run?
It depends on volume and refresh rate. For a keyword at about 59.6 posts a day, an hourly refresh is about $0.27 a month at $0.15 per 1,000 posts, versus about $8.95 for the same posts at the official X API's $0.005 per post read. See /pricing for subscription plans.
Can I track follower counts in Grafana too?
Yes. /twitter/user/info?userName=<account> returns followers and statusesCount. Use an Infinity stat panel for the current value, or poll it hourly into a table for a growth line; profiles cost 18 credits ($0.00018) each.
Continue
- Grafana: Infinity data source plugin
- Grafana: Infinity authentication and allowed hosts
- Grafana: alert rule queries and expressions
- Grafana: alert rule evaluation, pending period and states
- Grafana: PostgreSQL query editor macros
- X API pricing (official rate card)
- Twitter (X) API overview and endpoints
- Build a live hashtag dashboard in Streamlit
- Refreshable Twitter (X) data in Power BI
- Store Twitter (X) data in PostgreSQL
- Keyword alerts for Twitter (X), developer guide
- Monitoring Twitter (X) via API: polling vs webhooks
- TwitterAPI.io pricing and plans
- 01Twitter (X) Emotion Analysis in Python: Multi-Label Emotions on Real Posts, Model vs Lexicon
- 02Build a Tweet Summarizer for Twitter (X): Cited AI Digests in Python
- 03Twitter (X) Data in Splunk: Send Tweets to the HTTP Event Collector
- 04Twitter (X) API to Amazon S3: Partitioned JSONL and Parquet You Can Query with Athena
- 05Twitter (X) API + Apache Airflow: A Daily Tweet DAG You Can Backfill
- 06X Premium in 2026: The X Subscription Tiers, What They Unlock, and How to Cancel
- 07Twitter (X) Posts Not Loading? How to Fix It
- 08Twitter (X) Analytics Tools — A Developer's Honest Roundup
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.