Twitter (X) API to PostgreSQL: Table Design, Upserts and Indexes

- Key on the tweet id.
id bigint PRIMARY KEYplusON CONFLICT (id) DO UPDATE ... WHERE (...) IS DISTINCT FROM (...)makes every re-poll safe: 200 re-polled posts produced 32 row writes, exactly the ones whose counts had changed. - Two designs. One
jsonbrow per tweet keeps everything and needs no migrations; typedtweets/users/ edge tables are smaller (1,388 vs 8,255 bytes per tweet with indexes) and easier to join. - Index for the query you run. A
jsonb_path_opsGIN index serves@>containment; a GIN index on a generatedtsvectorcolumn serves full-text search. On 155,200 rows they were 67x and 33x faster than a sequential scan. - The GIN index on the whole document is big: 6.2 MB for 1,552 tweets, about 0.95x the table it indexes. Index the field you query, not the document, when space matters.
- Poll incrementally.
/twitter/tweet/advanced_searchwithfrom:operators andsince_time:<unix>set to your newest stored post minus a small overlap; the upsert absorbs the overlap. - Cost: 15 credits per tweet returned = $0.15 per 1,000 tweets; a check that finds nothing costs the $0.00015 minimum, so one query every 60 s for a month has a $6.48 floor. The official X API charges $0.005 per post read (about 33x more).
This guide is engine-generic: plain PostgreSQL that you run anywhere (a laptop, a VPS, Amazon RDS, Cloud SQL, Neon), filled by your own script. If you want a hosted Postgres where the scheduler, the function and the database are one product, the Supabase Twitter (X) API guide covers that path with Edge Functions and pg_cron; and if you prefer a document store over SQL, see storing tweets in MongoDB. Here the question is narrower and older than any host: what tables should tweets live in, how do you write them without duplicates, and which indexes pay off.
Every number below comes from a real run. We pulled 1,552 posts from 10 organization accounts (GitHub, Vercel, Supabase, Docker, OpenAI Developers, NVIDIA, NASA, AWS, Google Cloud, Cloudflare Developers) with the TwitterAPI.io read API, loaded them into a local PostgreSQL 16.2 started from the pgserver pip package, and measured payload sizes, bytes on disk per tweet for both designs, load times, re-poll duplicates and query times with and without GIN indexes. The SQL itself follows the PostgreSQL documentation for INSERT, JSON types, full-text search and GIN, which we cite as we go.
99.5% of posts re-polled 10 minutes later were already in the table, and 69% of those had new view, like or repost counts (10 organization accounts, 1,552 posts loaded into PostgreSQL 16.2, collected in 2026). Upsert with DO UPDATE, not DO NOTHING.
Two table designs: one JSONB document, or typed tables with edges
A tweet from the API is a nested JSON object: the post (id, text, createdAt, likeCount, retweetCount, replyCount, quoteCount, viewCount, bookmarkCount, conversationId, inReplyToId), its author object, entities (hashtags, URLs, mentions), media under extendedEntities, and sometimes a whole embedded quoted_tweet or retweeted_tweet. PostgreSQL can hold that in two reasonable shapes.
Design A: one jsonb row per tweet. A table with id bigint PRIMARY KEY and doc jsonb. You store exactly what the API returned and decide later what to query. The PostgreSQL docs describe jsonb as "stored in a decomposed binary format that makes it slightly slower to input due to added conversion overhead, but significantly faster to process, since no reparsing is needed", and note that jsonb supports indexing. They also say it does not keep key order, white space or duplicate keys, which does not matter for API payloads.
Design B: typed columns plus edges. A tweets table with the fields you actually filter and sort on, a users table keyed on the author id, and two edge tables, tweet_hashtags (tweet_id, tag) and tweet_mentions (tweet_id, user_id). This is classic Twitter database design: a post belongs to a user, and hashtags and mentions are many-to-many relations you can group and join.
In our sample, 440 of 1,552 posts were reposts and 117 were quotes, so the embedded retweeted_tweet / quoted_tweet objects are common. They also carry authors: the 1,552 posts referenced 304 distinct users once quoted and reposted authors are counted, plus 1,181 mention edges and 113 hashtag edges.
A common middle ground is both: typed columns for what you query, plus the raw doc kept in a side table (Design A) for anything you did not anticipate. The sizes below let you price that choice.
Step 1: create the tables (tweet id as a bigint primary key)
Tweet ids and user ids are 64-bit integers; the API returns them as strings, so cast them with int() and store them as bigint. Never store them as floating point or as JavaScript numbers: they exceed the 53-bit integer range of a double.
Use timestamptz for created_at. The API's createdAt looks like Thu Oct 16 12:34:56 +0000 2026, which Python parses with %a %b %d %H:%M:%S %z %Y into an aware datetime.
The tsv column is a stored generated column, the pattern the PostgreSQL full-text search docs show: GENERATED ALWAYS AS (to_tsvector('english', ...)) STORED, so it updates itself whenever text changes and a GIN index on it needs no trigger.
The schema below contains both designs. Pick one, or keep both as described above. The tweet_hashtags (tag) index is there for hashtag lookups through the edge table; we did not time it separately.
-- Design A: one JSONB document per tweet
CREATE TABLE tweets_raw (
id bigint PRIMARY KEY, -- the tweet id
doc jsonb NOT NULL, -- the tweet object exactly as the API returned it
fetched_at timestamptz NOT NULL DEFAULT now()
);
-- Design B: typed columns plus edge tables
CREATE TABLE users (
id bigint PRIMARY KEY,
user_name text NOT NULL,
name text,
followers integer,
following integer,
is_blue_verified boolean,
created_at timestamptz,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE tweets (
id bigint PRIMARY KEY,
author_id bigint NOT NULL REFERENCES users(id),
created_at timestamptz NOT NULL,
text text NOT NULL,
lang text,
like_count integer NOT NULL DEFAULT 0,
retweet_count integer NOT NULL DEFAULT 0,
reply_count integer NOT NULL DEFAULT 0,
quote_count integer NOT NULL DEFAULT 0,
view_count bigint,
bookmark_count integer,
conversation_id bigint,
in_reply_to_id bigint,
quoted_id bigint,
retweeted_id bigint,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED,
fetched_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE tweet_hashtags (
tweet_id bigint NOT NULL REFERENCES tweets(id) ON DELETE CASCADE,
tag text NOT NULL, -- lower-cased
PRIMARY KEY (tweet_id, tag)
);
CREATE TABLE tweet_mentions (
tweet_id bigint NOT NULL REFERENCES tweets(id) ON DELETE CASCADE,
user_id bigint NOT NULL,
PRIMARY KEY (tweet_id, user_id)
);
CREATE INDEX tweets_author_created ON tweets (author_id, created_at DESC);
CREATE INDEX tweet_hashtags_tag ON tweet_hashtags (tag);Step 2: upsert on the tweet id, and only rewrite rows that changed
Polling always re-reads posts you have: the newest page overlaps the last one, and a safety overlap on the time cursor adds more. The PostgreSQL docs define the tool for this: ON CONFLICT DO NOTHING "simply avoids inserting a row", while ON CONFLICT DO UPDATE "updates the existing row that conflicts", and in DO UPDATE the incoming row is available as the special excluded table.
Which one? Our re-poll answers it. After loading the sample we fetched the newest page of each account again and compared:
After 2 minutes every re-polled post was already stored, but 32 of them carried new numbers (32 a new viewCount, 5 a new likeCount, 2 a new retweetCount). After 10 minutes the pass found 1 new post and 199 stored ones, of which 138 had changed: all 138 in viewCount, 29 also in likeCount, 17 in retweetCount, 9 in replyCount. DO NOTHING would have kept stale counts on all of them. DO UPDATE without a condition would rewrite every duplicate (each rewrite creates a new row version that VACUUM later cleans up).
The WHERE ... IS DISTINCT FROM ... clause below rewrites only rows whose counts moved. Run against the 2-minute re-poll, it reported 32 affected rows, exactly the 32 we counted by comparing the JSON, and the table stayed at 1,552 rows. cur.rowcount therefore doubles as a "new or changed" counter for your logs.
Upsert users before tweets (the foreign key needs the author), and insert edge rows with ON CONFLICT DO NOTHING, since a hashtag or mention on a post never changes.
INSERT INTO tweets (id, author_id, created_at, text, lang, like_count, retweet_count,
reply_count, quote_count, view_count, bookmark_count, conversation_id,
in_reply_to_id, quoted_id, retweeted_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO UPDATE SET
like_count = EXCLUDED.like_count,
retweet_count = EXCLUDED.retweet_count,
reply_count = EXCLUDED.reply_count,
quote_count = EXCLUDED.quote_count,
view_count = EXCLUDED.view_count,
bookmark_count = EXCLUDED.bookmark_count,
fetched_at = now()
WHERE (tweets.like_count, tweets.retweet_count, tweets.reply_count,
tweets.quote_count, tweets.view_count)
IS DISTINCT FROM
(EXCLUDED.like_count, EXCLUDED.retweet_count, EXCLUDED.reply_count,
EXCLUDED.quote_count, EXCLUDED.view_count);Step 3: poll incrementally with a since_time cursor
The database is the cursor. Read max(created_at) from tweets, subtract a small overlap (10 minutes in the script below), and search for posts since then with /twitter/tweet/advanced_search. The TwitterAPI.io docs list from:<account> and since_time:<unix seconds> as query operators (docs.twitterapi.io/api-reference/endpoint/tweet_advanced_search), and each page returns up to 20 posts with has_next_page and next_cursor for the next one.
One query can cover several accounts: (from:github OR from:vercel OR from:NASA) since_time:1767225600. The overlap guarantees you never miss a post that was indexed a little late; the upsert from Step 2 turns the overlap into harmless no-op rows.
Use queryType=Latest so results come newest first. For keyword monitoring instead of accounts, replace the from: group with your terms; everything else stays the same. Our Kafka pipeline guide uses the same cursor idea when the destination is a topic instead of a table.
The complete, runnable poller is at the end of this article. It loops with a fixed 60-second sleep, upserts users, tweets, hashtags and mentions in one transaction per cycle, and prints how many rows were new or changed.
def search_since(since_unix):
query = "(" + " OR ".join(f"from:{a}" for a in ACCOUNTS) + f") since_time:{since_unix}"
params = {"query": query, "queryType": "Latest", "cursor": ""}
out = []
while True:
r = requests.get("https://api.twitterapi.io/twitter/tweet/advanced_search",
headers=HEADERS, params=params, timeout=30)
r.raise_for_status()
body = r.json()
out.extend(body.get("tweets") or [])
if not body.get("has_next_page") or not body.get("next_cursor"):
return out
params["cursor"] = body["next_cursor"]Step 4: backfills with COPY into a staging table
For a one-off backfill (an account's recent timeline, a past date range), you can stream rows with COPY ... FROM STDIN into a temporary staging table and then run one INSERT ... SELECT ... ON CONFLICT into the real table. The PostgreSQL docs describe COPY FROM as copying data "from a file to a table (appending the data to whatever is in the table already)", and STDIN means the data comes from the client connection; psycopg 3 exposes that as cursor.copy() with write_row().
At our sample size the difference was small. Median of 5 runs, 1,552 posts, one transaction each:
The JSONB loads took longer than the typed load, likely because each document is about 6,873 bytes of JSON to serialize, parse and compress, against a few hundred bytes of typed columns. Either way, loading is not the bottleneck: the API returns 20 posts per page, so a poller writes tens of rows per cycle, not thousands.
The PostgreSQL GIN docs give one bulk-load rule that does matter at scale: "for bulk insertions into a table it is advisable to drop the GIN index and recreate it after finishing bulk insertion", and "build time for a GIN index is very sensitive to the maintenance_work_mem setting".
import json
import psycopg
def bulk_load_raw(conn, tweets):
"""Backfill: COPY into a temp staging table, then one upsert into tweets_raw."""
with conn.transaction(), conn.cursor() as cur:
cur.execute("CREATE TEMP TABLE stage (id bigint, doc jsonb) ON COMMIT DROP")
with cur.copy("COPY stage (id, doc) FROM STDIN") as cp:
for t in tweets:
cp.write_row((int(t["id"]), json.dumps(t)))
cur.execute("""
INSERT INTO tweets_raw (id, doc)
SELECT DISTINCT ON (id) id, doc FROM stage
ON CONFLICT (id) DO UPDATE SET doc = EXCLUDED.doc, fetched_at = now()
""")Step 5: GIN indexes for JSONB containment and full-text search
Two query shapes come up in tweet archives: "posts whose JSON contains X" (a hashtag, a mentioned account, a media type) and "posts whose text matches these words". The PostgreSQL docs say the default jsonb GIN operator class supports ?, ?|, ?&, @>, @? and @@, while jsonb_path_ops supports only @>, @? and @@. For containment queries we used jsonb_path_ops. For text, a GIN index on the generated tsv column.
We timed both with EXPLAIN ANALYZE (median of 20 runs), forcing a sequential scan and then the index. On the real 1,552 rows the hashtag query took 10.5 ms without the index and 0.17 ms with it; the full-text query 0.12 ms vs 0.006 ms. Those are all fast. To see the trend, we copied the real rows 100 times with new ids (155,200 rows, synthetic volume, real content):
The planner picked the index on its own in every case once it existed. The catch is size: on the copied table the jsonb_path_ops index was 100 MB and took 9.3 s to build, while the full-text index was 12.8 MB and took 0.6 s. An index over the whole document indexes every key and value, including media URLs and the author profile.
If you only ever ask for hashtags, the typed tweet_hashtags table is the lean option: for our 1,552 posts it took 64 KB including its primary key, against 6.2 MB for the document-wide GIN index. The docs also note the GIN pending list (fastupdate) can slow searches if it grows large; for a write-light poller the default is fine.
-- JSONB containment (@>): jsonb_path_ops supports @>, @? and @@, not the key-exists operators
CREATE INDEX tweets_raw_doc_gin ON tweets_raw USING GIN (doc jsonb_path_ops);
SELECT count(*) FROM tweets_raw
WHERE doc @> '{"entities": {"hashtags": [{"text": "NVIDIAGTC"}]}}';
-- Full-text search on the generated tsvector column
CREATE INDEX tweets_tsv_gin ON tweets USING GIN (tsv);
SELECT id, created_at, text FROM tweets
WHERE tsv @@ websearch_to_tsquery('english', 'open source')
ORDER BY created_at DESC
LIMIT 20;
-- Typed design: hashtags through the edge table
SELECT t.id, t.created_at, t.like_count
FROM tweet_hashtags h JOIN tweets t ON t.id = h.tweet_id
WHERE h.tag = 'nvidiagtc'
ORDER BY t.created_at DESC;
What it costs: bytes on disk and dollars for the data
The median tweet object from the API was 6,873 bytes of JSON (95th percentile 19,060, largest 67,428; posts with an embedded quoted or reposted tweet carry a second full object). Stored as jsonb, the median value took 2,956 bytes, because PostgreSQL compresses large values: the docs say TOAST kicks in when a row is wider than TOAST_TUPLE_THRESHOLD (normally 2 kB). In our JSONB table, 95.9% of the bytes sat in the TOAST table, not the main heap.
Bytes per tweet are pg_total_relation_size (heap + TOAST + indexes) divided by the tweet count; for the typed design it is all four tables. The 1M column is plain multiplication of the measured value, not a separate test, and real growth also depends on dead row versions between vacuums.
The takeaway: typed tables were about 6x smaller than the JSONB table with its document-wide GIN index. If you keep raw JSON, keep it for replay and audits, and index the few fields you query.
PostgreSQL itself is free; the data is the line item. TwitterAPI.io bills 15 credits per tweet returned, which is $0.15 per 1,000 tweets, with a 15-credit minimum per request: a full 20-post page costs $0.003, and a check that finds nothing costs $0.00015. No X account is needed for reads.
The X rates are from docs.x.com/x-api/getting-started/pricing, which also caps pay-per-usage at 3 million post reads per monthly billing cycle. Per 1,000 posts, $5 against $0.15 is about 33x.
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 current amount and plans. Rate limits are 0.2 requests per second before the first payment and 20 once paid, which is plenty for a poller that runs once a minute.

Queries you can run once the tweets are in
With typed tables, everyday analytics is plain SQL: posts per day per account, median engagement, top hashtags, which accounts get mentioned together. With the JSONB table you can still reach any field with -> and ->>. The examples below run on the schema from Step 1.
If your analysis lives in notebooks, you can read these tables straight into a DataFrame; the pandas guide covers that side. For a warehouse that bills per query instead of a database you run, compare the BigQuery version.
-- Daily post count and median likes per account (last 30 days)
SELECT u.user_name,
date_trunc('day', t.created_at) AS day,
count(*) AS posts,
percentile_cont(0.5) WITHIN GROUP (ORDER BY t.like_count) AS median_likes
FROM tweets t JOIN users u ON u.id = t.author_id
WHERE t.created_at > now() - interval '30 days'
GROUP BY 1, 2
ORDER BY 1, 2;
-- Top hashtags this week
SELECT h.tag, count(*) AS uses
FROM tweet_hashtags h JOIN tweets t ON t.id = h.tweet_id
WHERE t.created_at > now() - interval '7 days'
GROUP BY h.tag ORDER BY uses DESC LIMIT 20;
-- Accounts mentioned together with a given account (co-mention edges)
SELECT m2.user_id, count(*) AS together
FROM tweet_mentions m1 JOIN tweet_mentions m2
ON m1.tweet_id = m2.tweet_id AND m1.user_id <> m2.user_id
WHERE m1.user_id = 1234567890
GROUP BY m2.user_id ORDER BY together DESC LIMIT 20;
-- Pull one field out of the raw document when you need it later
SELECT doc->'author'->>'userName' AS account, doc->>'lang' AS lang, count(*)
FROM tweets_raw GROUP BY 1, 2 ORDER BY 3 DESC;How we collected this
Question. What do real tweets look like once they are in PostgreSQL: payload size, bytes on disk for a JSONB design and a typed design, load time, how many re-polled posts are duplicates and how many of those changed, and what GIN indexes do to query time.
Accounts. 10 organization accounts: GitHub, Vercel, Supabase, Docker, OpenAI Developers, NVIDIA, NASA, AWS, Google Cloud and Cloudflare Developers.
Method. /twitter/user/last_tweets (replies excluded, the default), up to 8 pages per account, then one more page per account for the re-poll. 100 requests, 1,952 posts returned, about $0.29 at $0.15 per 1,000. Loaded with psycopg 3 into a local PostgreSQL 16.2 started from the pgserver pip package on an Apple silicon laptop. Load times are medians of 5 runs; query times are EXPLAIN ANALYZE execution times, medians of 20 runs.
Window and size. The latest posts of each account at collection time, collected in 2026: 1,552 distinct posts. The 155,200-row scale test is the same rows copied 100 times with new ids, so its content is real but its volume is synthetic.
What the sample cannot show. Timings on your server will differ (disk, memory, maintenance_work_mem, concurrent load, a managed host's network). Only organization accounts were sampled; personal accounts may carry fewer media and links, and so smaller JSON, which we did not measure. The re-poll covers two short intervals; we did not measure how long counts keep changing after that.
Privacy. Aggregates only. Organization accounts are named; authors of reposted or quoted posts are counted, never listed. Raw API pages stayed on the collecting machine; the published sample.json holds de-identified rows without ids, URLs, text or handles.
"""tweets_to_postgres.py - poll chosen X (Twitter) accounts with TwitterAPI.io and
upsert every new or changed post into plain PostgreSQL (any host: local, RDS,
Cloud SQL, Neon, Supabase, a VPS).
pip install requests "psycopg[binary]"
export TWITTERAPI_IO_KEY=... # from your dashboard
export DATABASE_URL=postgresql://user:pass@host:5432/db
python tweets_to_postgres.py # Ctrl+C to stop
Create the tables first with the schema from the article (Design B).
"""
import os
import time
from datetime import datetime, timedelta, timezone
import psycopg
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
ACCOUNTS = ["github", "vercel", "supabase", "Docker", "NASA"]
POLL_SECONDS = 60 # fixed pacing
OVERLAP = timedelta(minutes=10) # re-read a little; the upsert absorbs duplicates
UPSERT_USER = """
INSERT INTO users (id, user_name, name, followers, following, is_blue_verified, created_at)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO UPDATE SET
user_name = EXCLUDED.user_name, name = EXCLUDED.name,
followers = EXCLUDED.followers, following = EXCLUDED.following,
is_blue_verified = EXCLUDED.is_blue_verified, updated_at = now()
"""
UPSERT_TWEET = """
INSERT INTO tweets (id, author_id, created_at, text, lang, like_count, retweet_count,
reply_count, quote_count, view_count, bookmark_count, conversation_id,
in_reply_to_id, quoted_id, retweeted_id)
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (id) DO UPDATE SET
like_count = EXCLUDED.like_count, retweet_count = EXCLUDED.retweet_count,
reply_count = EXCLUDED.reply_count, quote_count = EXCLUDED.quote_count,
view_count = EXCLUDED.view_count, bookmark_count = EXCLUDED.bookmark_count,
fetched_at = now()
WHERE (tweets.like_count, tweets.retweet_count, tweets.reply_count,
tweets.quote_count, tweets.view_count)
IS DISTINCT FROM
(EXCLUDED.like_count, EXCLUDED.retweet_count, EXCLUDED.reply_count,
EXCLUDED.quote_count, EXCLUDED.view_count)
"""
def parse_time(s):
# "Thu Oct 16 12:34:56 +0000 2026"
return datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y") if s else None
def to_int(v):
try:
return int(v)
except (TypeError, ValueError):
return None
def search_since(since_unix):
"""All posts from ACCOUNTS since a Unix time, following next_cursor."""
query = "(" + " OR ".join(f"from:{a}" for a in ACCOUNTS) + f") since_time:{since_unix}"
params = {"query": query, "queryType": "Latest", "cursor": ""}
out = []
while True:
r = requests.get(f"{BASE}/twitter/tweet/advanced_search",
headers=HEADERS, params=params, timeout=30)
r.raise_for_status()
body = r.json()
out.extend(body.get("tweets") or [])
if not body.get("has_next_page") or not body.get("next_cursor"):
return out
params["cursor"] = body["next_cursor"]
def user_row(a):
return (int(a["id"]), a.get("userName") or "", a.get("name"), a.get("followers"),
a.get("following"), a.get("isBlueVerified"), parse_time(a.get("createdAt")))
def tweet_row(t):
return (int(t["id"]), int(t["author"]["id"]), parse_time(t["createdAt"]),
t.get("text") or "", t.get("lang"),
t.get("likeCount") or 0, t.get("retweetCount") or 0,
t.get("replyCount") or 0, t.get("quoteCount") or 0,
t.get("viewCount"), t.get("bookmarkCount"),
to_int(t.get("conversationId")), to_int(t.get("inReplyToId")),
to_int((t.get("quoted_tweet") or {}).get("id")),
to_int((t.get("retweeted_tweet") or {}).get("id")))
def save(conn, tweets):
"""Upsert users first (foreign key), then tweets, then hashtag and mention edges."""
written = 0
with conn.transaction(), conn.cursor() as cur:
users = {}
for t in tweets:
for a in (t.get("author"), (t.get("quoted_tweet") or {}).get("author"),
(t.get("retweeted_tweet") or {}).get("author")):
if a and a.get("id"):
users[a["id"]] = a
cur.executemany(UPSERT_USER, [user_row(a) for a in users.values()])
for t in tweets:
cur.execute(UPSERT_TWEET, tweet_row(t))
written += cur.rowcount # 1 = new or changed, 0 = unchanged duplicate
ent = t.get("entities") or {}
for h in ent.get("hashtags") or []:
cur.execute("INSERT INTO tweet_hashtags VALUES (%s, %s) ON CONFLICT DO NOTHING",
(int(t["id"]), h["text"].lower()))
for m in ent.get("user_mentions") or []:
if m.get("id_str"):
cur.execute("INSERT INTO tweet_mentions VALUES (%s, %s) ON CONFLICT DO NOTHING",
(int(t["id"]), int(m["id_str"])))
return written
def cursor_time(conn):
"""Resume point = newest stored post minus an overlap, or 24 hours ago on first run."""
with conn.cursor() as cur:
cur.execute("SELECT max(created_at) FROM tweets")
newest = cur.fetchone()[0]
start = (newest - OVERLAP) if newest else datetime.now(timezone.utc) - timedelta(hours=24)
return int(start.timestamp())
def main():
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
while True:
try:
tweets = search_since(cursor_time(conn))
written = save(conn, tweets)
print(f"{datetime.now():%H:%M:%S} returned={len(tweets)} new_or_changed={written}")
except requests.RequestException as e:
print("API error, retrying next cycle:", e)
time.sleep(POLL_SECONDS)
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
Should I store tweets as JSONB or in normal columns in PostgreSQL?
Columns for anything you filter, sort or join on; JSONB if you want the full payload without deciding the schema up front. In our test the typed tables took 1,388 bytes per tweet with indexes and the JSONB table with a GIN index took 8,255. You can also keep both: typed columns for queries and the raw document for replay.
What data type should a tweet id use in Postgres?
bigint. Tweet and user ids are 64-bit integers that the API returns as strings. Cast with int() and make the tweet id the primary key so ON CONFLICT (id) can deduplicate. Avoid floating point or JavaScript numbers, which lose precision above 2^53.
How do I avoid duplicate tweets when polling?
Make the tweet id the primary key and write with INSERT ... ON CONFLICT (id) DO UPDATE. Overlap is normal: re-polling the newest page of 10 accounts 2 minutes after loading returned 100% posts we already had, and 99.5% after 10 minutes. Add WHERE (...) IS DISTINCT FROM (...) so only rows with changed counts are rewritten.
Should the upsert use DO NOTHING or DO UPDATE?
DO UPDATE, if you want current engagement numbers. 69% of the duplicates in our 10-minute re-poll had a changed view, like or repost count; DO NOTHING would have kept the old numbers. Use DO NOTHING for edge tables (hashtags, mentions), which never change for a given post.
Do I need a GIN index on the JSONB column?
Only if you query inside the document with @>, @? or @@. It made a hashtag containment query about 67x faster on 155,200 rows, but the index was about 0.95x the size of the table it indexed. If you query one path, index that path or use a typed edge table instead.
How do I do full-text search on tweets in PostgreSQL?
Add a stored generated column tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED, create a GIN index on it, and query with tsv @@ websearch_to_tsquery('english', 'your words'). This is the pattern from the PostgreSQL full-text search docs. For multilingual posts, use the lang field to choose a configuration or the simple configuration.
Is this different from storing tweets in Supabase?
Supabase is hosted Postgres, so the SQL here works there too. The difference is the runtime: the Supabase guide runs the poller as an Edge Function scheduled by pg_cron, while this guide uses a plain Python script against any PostgreSQL server.
How much does it cost to collect tweets for a Postgres database?
With TwitterAPI.io, $0.15 per 1,000 tweets returned and a $0.00015 minimum per request, so polling once a minute with no new posts costs about $6.48 a month. The official X API lists $0.005 per post read, $5 per 1,000. PostgreSQL itself is free.
Continue
- PostgreSQL docs: INSERT and ON CONFLICT (DO NOTHING, DO UPDATE, excluded)
- PostgreSQL docs: JSON types, jsonb indexing and GIN operator classes
- PostgreSQL docs: full-text search tables and indexes (generated tsvector column)
- PostgreSQL docs: GIN indexes (fastupdate, bulk-load advice)
- TwitterAPI.io docs: advanced search (from:, since_time:, cursor)
- X developer docs: pay-per-usage pricing
- X (Twitter) API overview and endpoints
- Store tweets in Supabase (hosted Postgres with Edge Functions)
- Store tweets in MongoDB
- Load tweets into BigQuery
- Analyze Twitter data with pandas
- Stream tweets into Kafka
- TwitterAPI.io pricing and plans
- TwitterAPI.io API reference
- 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) Data in Grafana: Mention Dashboards and Spike Alerts
- 06Twitter (X) API in Kotlin: Ktor, kotlinx.serialization and coroutines
- 07MCP vs CLI for AI agents: token cost, auth and reliability, measured on Twitter (X) data
- 08X Chat API: Building on Encrypted Twitter (X) DMs with the Chat XDK
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.