Twitter (X) API + Redis: Cache, Dedupe and Queue Tweets in Python

- Four Redis keys do the work:
hw:<query>(newest seen time),seen:<query>(SET of ids),tweets(STREAM for workers),rl:<second>(INCR rate counter). - Dedup is a billing issue, not just hygiene: re-polling page 1 every 60 s returned 94.2% already-seen tweets after the first round, and each one is billed at 15 credits.
- since_time from Redis cut the polling bill 77.9%: 420 tweets billed on the plain query versus 89 with the mark, over the same seven rounds of three searches.
- Back the mark off a little: the plain arm found 81 new ids and the since_time arm 75, so leave a short overlap and let
SADDabsorb the repeats. - Do not build a profile cache first: only 11.9% of author lookups repeated within 24 h, and
authoris already inside every tweet object. - Store lean hashes: a median 402 bytes per tweet for 10 fields versus 3,737 bytes of full JSON, about 41 MB versus 464 MB per 100,000 tweets before Redis overhead.
This guide is about putting Redis between a Twitter (X) API poller and the code that uses the tweets: deduping, remembering where you left off, queueing work and pacing requests. If you want a durable event log with replay across many services, that is the Twitter API with Kafka guide; if you want tweets stored for SQL queries and history, that is Twitter API with PostgreSQL. Redis is the fast, in-memory layer that sits in front of either.
The reason to care is billing. TwitterAPI.io charges 15 credits per tweet returned ($0.15 per 1,000 tweets), with a 15-credit minimum per request, so a poller that keeps asking for the same first page pays again for tweets it already has. We measured how much that costs and how much a few Redis keys save, using a real polling run on three searches and five organization timelines, collected in 2026.
Everything below uses requests against https://api.twitterapi.io with the X-API-Key header, and redis-py for Redis. Redis command behavior is quoted from the redis.io command reference. No X account is needed for any of these reads.
77.9%
The four Redis keys a tweet poller needs
A polling pipeline has four problems: it must know where it stopped, it must not process a tweet twice, it must hand work to other processes, and it must not exceed its own request budget. Each maps onto one Redis data type.
Why a SET and not a Bloom filter. Per the redis.io SADD reference, the command returns the number of members that were added, not counting members already present, at O(1) per member. That return value is your dedup decision: 1 means new, 0 means seen. A SET of 64-bit tweet ids stays small for the volumes a single poller sees, and it is exact; a probabilistic filter only becomes worth it at much larger scale.
Why a STRING for the mark. One value per query, overwritten after each poll. The advanced_search docs on docs.twitterapi.io describe since_time: and until_time: as Unix seconds inside the query string, so the mark is just an integer.
An optional fifth key. A user:<id> HASH with a TTL can cache profiles, but our data below shows it pays off far less than the first four for search-driven pipelines.
What re-polling costs without Redis: the polling study
We ran two pollers side by side for eight rounds, 60 seconds apart, on three searches (redis, kafka, postgres, queryType Latest). The plain arm asked for page 1 of each query every round, which is what many first versions of a bot do. The since_time arm read a high-water mark from Redis and asked only for tweets at or after it. Both arms pushed every returned id through SADD. The eighth round hit a 503 wave on search and returned nothing for either arm, so the numbers cover seven complete rounds, 21 successful requests per arm.
After the first round, 94.2% of the tweets the plain arm received were already in its SET (360 returned, 21 new over 18 requests). Without Redis that is 339 repeats a downstream worker would process twice; with only a SET it is 339 repeats you still pay for. The mark is what moves the bill: 4,905 fewer credits, 77.9% of the polling cost, on three quiet developer-topic searches.
The boundary repeat is expected. The since_time arm saw 14 duplicates, roughly one per poll: the tweet sitting exactly at the mark comes back on the next request. The SADD check absorbs it, which is why you keep the SET even when you use a mark.
Leave a small overlap. The plain arm found 81 new ids and the since_time arm 75 over the same rounds. A likely cause is that search results can include a tweet a little after its createdAt, so a mark set exactly at the newest timestamp can step over a late arrival. Backing the mark off by 60 seconds costs a few repeat tweets per poll and lets the SET drop them.

Steps 1 and 2: dedupe with a SET, resume with a since_time mark
Pipe the ids of every returned page through SADD before you do anything else with the tweets. Use a pipeline so a 20-tweet page costs one round trip to Redis, and keep only tweets whose SADD result is 1.
Give the SET an expiry so it cannot grow forever. A 7-day EXPIRE refreshed on each write is plenty for a poller that looks back minutes, and per the redis.io eviction guide, keys with a TTL are also the ones the volatile-* policies can evict under memory pressure.
One SET per query or one global SET? Per query if different queries feed different consumers; global if the same tweet matching two queries should be processed once. In our run the three topics barely overlapped, so either works; pick based on what your workers do.
After each poll, write the newest createdAt you saw into hw:<query> as Unix seconds, and build the next query as <query> since_time:<mark minus 60>. Tweet createdAt arrives as a string like Thu Oct 16 12:34:56 +0000 2026, so parse it with %a %b %d %H:%M:%S %z %Y.
Follow pages until nothing is new. In our run has_next_page stayed true even on since_time pages that held one tweet, so a loop that follows next_cursor blindly pays a 15-credit minimum for each extra request. Stop when a page adds no new ids to the SET, or when its oldest tweet is older than the mark.
Survive restarts. Because the mark lives in Redis and not in process memory, a crashed or redeployed poller resumes where it stopped instead of re-reading a full page. With Redis persistence (RDB or AOF) enabled, it also survives a Redis restart.
The plain arm in our study is what you get without this step: 60 tweets billed every minute for three queries, whether anything happened or not. Cost of the floor alone, from the TwitterAPI.io rate card: a check that finds nothing costs $0.00015; every 60 seconds for a month that is 43,200 checks, or $6.48 per query.
import redis
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def only_new(query_key, tweets):
"""Return tweets whose id was not already in the SET (SADD returns 1 for new)."""
pipe = r.pipeline()
for t in tweets:
pipe.sadd(f"seen:{query_key}", t["id"])
pipe.expire(f"seen:{query_key}", 7 * 86400)
added = pipe.execute()[:-1]
return [t for t, a in zip(tweets, added) if a == 1]Step 3: hand new tweets to workers with Redis Streams
Once a tweet passes the SET, XADD it to a stream and let workers read it through a consumer group. Per the redis.io XREADGROUP reference, reading with the special id > returns only messages never delivered to any other consumer, each delivered message is stored in the group's Pending Entries List until the worker calls XACK, and a worker that crashed can re-read its pending messages by starting with id 0. That gives you at-least-once processing without writing a queue.
Cap the stream length. Use XADD tweets MAXLEN ~ 100000 * ... so the stream trims itself; the ~ lets Redis trim in efficient chunks rather than exactly.
Store lean fields. Stream entries are field-value pairs, so write the handful of fields your workers need (id, text, createdAt, counts, author userName) rather than the full JSON object. The memory section below shows the difference is about nine times.
Several workers, one group. Two workers in the same group split the messages between them; two groups each get every message. Use one group per downstream job (for example alerts and archive).
import json
import redis
r = redis.Redis(decode_responses=True)
try:
r.xgroup_create("tweets", "alerts", id="0", mkstream=True)
except redis.ResponseError:
pass # group already exists
def handle(fields):
print(fields["createdAt"], fields["author"], fields["text"][:80])
# first drain this worker's pending entries (id 0), then read new ones (>)
start = "0"
while True:
resp = r.xreadgroup("alerts", "worker-1", {"tweets": start}, count=50, block=5000)
entries = resp[0][1] if resp else []
if start == "0" and not entries:
start = ">"
continue
for msg_id, fields in entries:
handle(fields)
r.xack("tweets", "alerts", msg_id)Step 4: a Redis rate limiter for your own QPS
TwitterAPI.io allows 0.2 requests per second before the first payment, 20 once paid, 50 on Scale and 500 on Business, with higher limits on request. If several pollers or a burst of backfill jobs share one key, a Redis counter keeps them under that number together. When you do go over, the rate limit exceeded guide covers the 429 handling.
The redis.io INCR reference describes the simplest version: one counter per second, incremented and given a short expiry inside MULTI/EXEC, and the call is allowed only if the counter is at or below the limit. The same page warns that the single-counter variant has a race unless you wrap INCR plus EXPIRE in a Lua script; the per-second key with a transaction avoids it.
Wait, do not drop. When the counter is over the limit, sleep until the next second and try again. Use a fixed wait; the point is pacing your own traffic to your plan, nothing more.
import time
import redis
r = redis.Redis(decode_responses=True)
LIMIT_PER_SECOND = 20 # your plan's limit, shared by every process using this key
def acquire():
while True:
second = int(time.time())
key = f"rl:{second}"
pipe = r.pipeline() # MULTI/EXEC
pipe.incr(key)
pipe.expire(key, 10)
count, _ = pipe.execute()
if count <= LIMIT_PER_SECOND:
return
time.sleep(second + 1 - time.time())Profile caching and memory: what a Redis tweet cache costs
A classic Redis pattern is a read-through cache for user lookups: check user:<id>, call /twitter/user/info on a miss, store the result with a TTL. Profiles cost 18 credits each ($0.18 per 1,000), so it looks attractive. We replayed the 353 search tweets of our study in time order through a cache keyed by author id with a 24-hour TTL.
Topic searches are spread across many different people, so a profile cache barely fires. More important, every tweet object already carries an author object with followers, isBlueVerified, createdAt and more, so a pipeline that only needs those fields should make no profile call at all. A profile cache earns its keep when you monitor a fixed list of accounts or enrich mentions of your own account, where the same handles recur all day.
If you do cache, pick the policy. The redis.io eviction guide lists allkeys-lru as a good default when you have no reason to prefer another policy, and gives the hit rate as keyspace_hits / (keyspace_hits + keyspace_misses) from INFO stats, which is the number to watch.
We serialized all 665 unique tweet objects from the study (search and timelines) and measured them. Redis adds per-key overhead on top of these numbers; check a real key with MEMORY USAGE before sizing an instance.
The full object is large because it carries the full author profile, entities, media variants and quoted or retweeted tweets. The lean form keeps id, text, createdAt, lang, like, retweet, reply, quote and view counts, and the author's userName. For a hot layer that feeds workers and dashboards, the lean form is enough; keep the full JSON in a database such as PostgreSQL or MongoDB if you need it later.
Per the redis.io eviction guide, maxmemory set to 0 means no limit on 64-bit systems, so set it explicitly for a cache, and leave headroom for replication and persistence buffers, which are not counted against the limit.

How often to poll, and when to graduate to Kafka
Polling frequency should follow how often the source actually posts. Our five organization timelines show how quiet even large accounts are:
Even @awscloud posts about five times a day, so a 60-second poll on one of these accounts comes back empty well over 99% of the time. Combine accounts into one from:a OR from:b search with a since_time mark, poll every few minutes, and the floor cost drops to about $1.30 a month at a 5-minute interval. The Twitter API pagination guide covers the cursor loop for backfills.
Graduate to Kafka when several teams need the same tweets with independent replay, you need retention measured in days or weeks with offsets per consumer, or throughput reaches the point where one Redis instance's memory is the constraint. Until then, a Redis stream with a consumer group covers a single product's workers with far less to operate.
Cost: TwitterAPI.io with Redis vs the official X API
Redis changes how many tweets you are billed for; the rate card decides what each one costs. Both prices below come from the providers' own pages, fetched for this guide.
Per 1,000 tweets that is about 33 times less on TwitterAPI.io ($5 / $0.15). The Redis savings apply on either side: the 331 tweets the since_time mark avoided in our seven rounds would have cost $0.05 on TwitterAPI.io and $1.66 on the official pay-per-usage rate. New TwitterAPI.io accounts get free starter credits (no card, one per person or network, expiring after 31 days); the amount is on the pricing page. Purchased credits never expire.
The official X API offers $20 in credits when you save a first eligible card and complete a first purchase, and matches a first auto-recharge up to $50, per docs.x.com/x-api/getting-started/pricing.
How we collected this
Question. How much does a Redis hot layer save a tweet poller: duplicates dropped by a SET, billed tweets avoided by a since_time mark, profile lookups avoided by a cache, and the memory a tweet cache needs.
Queries and accounts. Searches redis, kafka and postgres (queryType Latest) on /twitter/tweet/advanced_search; timelines of five organization accounts (@redisinc, @github, @vercel, @Docker, @awscloud) on /twitter/user/last_tweets.
Window and sample. The latest posts at collection time, collected in 2026: a backfill of up to 8 search pages per query (the redis backfill failed on a 503 wave and is not included) and 4 timeline pages per account, plus an eight-round polling run 60 seconds apart, of which seven rounds completed. 665 unique tweets in total; 78 successful requests, 17,145 credits ($0.17).
Redis. No Redis server was installed on the collection machine, so the study used fakeredis, a pure-Python Redis stand-in, for SADD, GET/SET and HSET. The counts above do not depend on Redis internals; command semantics and the patterns in Steps 3 and 4 are taken from the redis.io reference and were not load-tested here.
What the sample cannot show. Seven minutes of polling on three moderate developer topics. A busy brand or breaking-news query will return far more new tweets per poll, so the duplicate share falls and since_time saves less; quieter account lists save more. Author repeat rates depend heavily on the query.
Privacy. Aggregates only. Only organization accounts are named; raw search pages, which include private individuals, were kept out of the published dataset, and the shared sample holds de-identified rows with no ids, URLs, text or handles.
"""Poll Twitter (X) searches through a Redis hot layer: since_time mark, SET dedup, stream for workers, rate limit.
pip install requests redis # needs a running Redis server on localhost:6379
"""
import os
import time
from datetime import datetime
import redis
import requests
BASE = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
QUERIES = ["redis", "kafka", "postgres"]
OVERLAP = 60 # seconds to step back from the mark; SADD drops the repeats
LIMIT_PER_SECOND = 20 # your plan's limit
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
def ts(t):
return int(datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y").timestamp())
def acquire():
while True:
second = int(time.time())
pipe = r.pipeline()
pipe.incr(f"rl:{second}")
pipe.expire(f"rl:{second}", 10)
if pipe.execute()[0] <= LIMIT_PER_SECOND:
return
time.sleep(second + 1 - time.time())
def poll(query):
mark = r.get(f"hw:{query}")
q = f"{query} since_time:{int(mark) - OVERLAP}" if mark else query
cursor, newest, queued = "", int(mark or 0), 0
while True:
acquire()
resp = requests.get(f"{BASE}/twitter/tweet/advanced_search", headers=HEADERS,
params={"query": q, "queryType": "Latest", "cursor": cursor}, timeout=30)
if resp.status_code != 200:
print("http", resp.status_code, "- retry next round")
return queued
body = resp.json()
tweets = body.get("tweets", [])
pipe = r.pipeline()
for t in tweets:
pipe.sadd(f"seen:{query}", t["id"])
added = pipe.execute()
r.expire(f"seen:{query}", 7 * 86400)
fresh = [t for t, a in zip(tweets, added) if a == 1]
for t in fresh:
r.xadd("tweets", {
"id": t["id"], "query": query, "createdAt": t["createdAt"], "text": t["text"],
"author": t["author"]["userName"], "likeCount": t.get("likeCount", 0),
"retweetCount": t.get("retweetCount", 0), "viewCount": t.get("viewCount") or 0,
}, maxlen=100000, approximate=True)
newest = max(newest, ts(t))
queued += len(fresh)
# stop when nothing new came back, even if has_next_page is still true
if not fresh or not body.get("has_next_page") or not body.get("next_cursor"):
break
cursor = body["next_cursor"]
if newest:
r.set(f"hw:{query}", newest)
return queued
if __name__ == "__main__":
while True:
started = time.time()
for query in QUERIES:
print(query, "queued", poll(query), "new tweets")
time.sleep(max(0, 300 - (time.time() - started))) # fixed 5-minute pacingResearching this?Free starter credits cover end-to-end testing — Google sign-in, no card. Get a key.
Questions readers ask
How do I cache Twitter API responses in Redis?
Do not cache whole responses keyed by URL; for a poller that just replays stale pages. Instead keep the state that changes what you request: a hw:<query> STRING with the newest createdAt you saw (sent back as since_time:), and a seen:<query> SET of tweet ids checked with SADD. In our study that combination cut billed tweets by 77.9% compared with re-fetching page 1 every 60 seconds.
How do I avoid processing the same tweet twice?
Run every returned id through SADD seen:<query> <id> and keep only tweets where the command returns 1. Per the redis.io reference it returns the number of members actually added, so 0 means the id was already there. Keep the SET even when you use since_time: the tweet at the boundary of the mark comes back on the next poll, which happened about once per poll in our run.
Can Redis help with Twitter API rate limits?
Yes, for your own side of the limit. A per-second counter (INCR rl:<second> plus EXPIRE inside MULTI/EXEC, the pattern on the redis.io INCR page) lets several processes share one budget, for example 20 requests per second on a paid TwitterAPI.io plan. Over the limit, wait until the next second. It does not raise the limit; for 429 handling see the rate limit exceeded guide.
Should I use Redis Streams or Kafka for tweets?
Redis Streams with a consumer group is enough for one product's workers: XREADGROUP with > gives each worker new messages, unacknowledged ones stay pending until XACK, and MAXLEN ~ keeps the stream bounded. Move to Kafka when several teams need the same tweets with independent replay, long retention, or throughput beyond what one Redis instance's memory holds.
How much memory does Redis need to cache tweets?
In our sample a full tweet object serialized to a median 3,737 bytes (p90 8,534), about 464 MB per 100,000 tweets, while a 10-field lean hash was a median 402 bytes, about 41 MB per 100,000. Redis adds per-key overhead on top, so measure a real key with MEMORY USAGE and set maxmemory explicitly.
Is it worth caching Twitter user profiles in Redis?
For topic searches, rarely: only 11.9% of author lookups in our sample repeated within 24 hours, and each tweet already embeds its author object with follower counts and verification flags. A profile cache with a TTL is worth it when you track a fixed list of accounts or your own mentions, where the same users recur.
What does polling the Twitter API every minute cost?
On TwitterAPI.io a check that returns nothing costs the $0.00015 minimum, so every 60 seconds for a month is 43,200 checks, $6.48 per query; every 5 minutes is $1.30. Tweets that come back are billed at $0.15 per 1,000, which is why repeats matter: re-polling page 1 billed 420 tweets in our run where the since_time mark billed 89.
Continue
- Redis docs: SADD return value and complexity
- Redis docs: XREADGROUP, consumer groups and the Pending Entries List
- Redis docs: INCR and the rate limiter pattern
- Redis docs: maxmemory and eviction policies
- TwitterAPI.io docs: advanced search, since_time and pagination
- X API pay-per-usage pricing
- X (Twitter) API guides and endpoints hub
- Stream tweets into Kafka for replay across services
- Store tweets in PostgreSQL for SQL queries
- Twitter API pagination with next_cursor
- Fix Twitter API rate limit exceeded errors
- Save tweets to MongoDB
- TwitterAPI.io pricing per 1,000 tweets
- 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 in Swift: URLSession, async/await and Codable models
- 07X API 403 Forbidden: Every Cause on the Twitter (X) API and How to Fix Each One
- 08Twitter (X) to Apache Kafka: a Python Producer Keyed by Tweet ID
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.