Supabase + Twitter (X) API: store tweets in Postgres with an Edge Function and pg_cron

By TwitterAPI.io Team•13 min read
Pipeline diagram: pg_cron schedules pg_net, which calls a Supabase Edge Function that pages the TwitterAPI.io advanced search endpoint and upserts posts into a tweets table with RLS on
The whole pipeline lives inside one Supabase project. Numbers from 1,440 posts for one keyword, collected in 2026.
TL;DR
  • The stack: pg_cron fires, pg_net POSTs to an Edge Function (Deno, TypeScript), the function pages /twitter/tweet/advanced_search and upserts into public.tweets.
  • Dedup is the primary key: id text primary key + upsert(rows, { onConflict: "id" }). A re-run minutes later returned 36 of 40 posts we already had; the upsert updates their counters instead of adding rows.
  • Volume, measured: the keyword supabase produced about 408 posts a day (2,856 per 7 days) in a sample of 1,440 posts collected in 2026.
  • Storage: 52.38 MB per 30 days if you keep the raw JSON, 8.9 MB with the trimmed columns. The Free plan's 500 MB lasts about 286 days of raw JSON.
  • Schedule: every 5 to 15 minutes. Every minute costs $7.08 a month instead of $2.76, because each empty check still costs the 15-credit minimum.
  • RLS: alter table public.tweets enable row level security plus a select policy for authenticated. Keep the service role key inside the function, never in a browser.

This page is the Supabase version of a pattern we already cover for other platforms: the Cloudflare Workers guide runs the same poll on Workers Cron Triggers and keeps state in KV, and the Google Sheets guide appends rows to a spreadsheet. Here the scheduler, the function and the storage are all one Supabase project, so the table is a real Postgres table you can query with SQL, join with your own data and expose to your app behind Row Level Security.

Everything below is one worked example: the table schema, the Edge Function, the pg_cron job, the RLS policy, a Python backfill and the SQL you run afterwards. The numbers come from a real collection run on the keyword supabase: how many rows a day it writes, how many bytes each row takes, how many duplicates the upsert absorbs and what each pg_cron interval costs.

What we did and did not run. We collected the posts with our own read client and measured everything on the JSON the API returned. We did not have a Supabase project for this page, so the Edge Function, the cron job and the SQL were not deployed by us; they follow Supabase's docs as fetched for this page, and each Supabase fact below names the docs page it comes from.

Posts a day one keyword writes into Supabase

~408 rows, $1.84 / 30 days

01 — Section

The architecture: four Supabase pieces and one API call

Supabase Cron (pg_cron). Supabase's Cron guide describes it as built on the pg_cron Postgres extension, able to run jobs "anywhere from every second to once a year", with every run and its status recorded in cron.job_run_details. The guide recommends no more than 8 jobs running at once and no job longer than 10 minutes.

pg_net. The extension that lets Postgres make the HTTP request. Supabase's guide to scheduling Edge Functions pairs the two: the cron job's SQL calls net.http_post against the function's URL on your your-project-ref.supabase.co host.

An Edge Function. Supabase describes the runtime as the Supabase Edge Runtime, Deno compatible and TypeScript first. Per the limits page a function gets 256 MB of memory, 2 seconds of CPU time per request, and a wall clock of 150 s on the Free plan and 400 s on paid plans. Network waits do not count toward the CPU time, so paging an API is a good fit.

A Postgres table with RLS. The tweets table, keyed on the X post id, in the public schema with Row Level Security switched on.

The data source. GET /twitter/tweet/advanced_search on TwitterAPI.io with queryType=Latest, the since_time: operator and cursor pagination. It returns up to 20 posts per page in a top-level tweets[] array with has_next_page and next_cursor. Reads need an API key only, no X developer account.

PieceWhat it does hereLimit worth knowing
pg_cronfires every 5 minutesno more than 8 concurrent jobs recommended
pg_netPOSTs to the functiondecrypted secret sits in net.http_request_queue until sent
Edge Functionpages the API, upserts rows2 s CPU, 150 s (Free) / 400 s (paid) wall clock
public.tweetsstores and dedupesFree plan database: 500 MB per project
02 — Section

Step 1: the tweets table, keyed on the post id, with RLS on

The single decision that makes the whole pipeline safe to re-run is the primary key. X post ids are 64-bit integers; keep them as text so JavaScript never rounds them. With id as the primary key, an upsert either inserts a new post or updates the counters of one you already have, and a scheduled job that overlaps its previous run can never create a duplicate.

Columns vs raw JSON. The 14 typed columns cover what you will filter and sort on. The optional raw jsonb column keeps the whole tweet object, which is useful for fields you did not plan for (entities, extendedEntities.media, quoted_tweet, card). It is also the expensive part: in our sample the full JSON had a median of 2,850 bytes against 496 bytes for the trimmed row, and the nested author object alone was 33.0% of it.

The index. Every query below filters on keyword and a time range, and the Edge Function reads the newest created_at on every run, so (keyword, created_at desc) is the one index you need from day one.

Row Level Security, before the first insert.

Supabase's RLS guide puts it plainly: "Enable RLS on every table in an exposed schema." The public schema is exposed through the auto-generated REST API, so a tweets table without RLS is readable and writable by any role that has a grant on it.

Who writes. Only the Edge Function, using the service role key. Supabase's docs describe the service_role role as having full access that RLS does not restrict, and the secrets page says the secret keys belong in Edge Functions and never in a browser. That is why the schema below has no insert or update policy at all: nothing coming from a browser can write.

Who reads. The policy below lets any signed-in user select. If the feed is public, add anon to the role list (to authenticated, anon); if each customer tracks their own keywords, add a user_id uuid column and use using (user_id = auth.uid()) instead of using (true).

Author data. The rows hold public posts, many by private individuals. Keep the read policy as narrow as your product needs, and do not expose the raw JSON column to anon if you only show counts.

sql
-- 1. The table: one row per post, the tweet id is the primary key
create table public.tweets (
  id               text primary key,          -- X post id, kept as text (64-bit)
  keyword          text not null,             -- which tracked query found it
  created_at       timestamptz not null,
  author_id        text,
  author_username  text,
  text             text,
  lang             text,
  like_count       integer,
  retweet_count    integer,
  reply_count      integer,
  quote_count      integer,
  view_count       bigint,
  bookmark_count   integer,
  conversation_id  text,
  is_reply         boolean,
  raw              jsonb,                     -- optional: the whole tweet object
  fetched_at       timestamptz not null default now()
);

create index tweets_keyword_created_idx on public.tweets (keyword, created_at desc);

-- 2. RLS: the table lives in the exposed public schema, so switch it on
alter table public.tweets enable row level security;

-- Signed-in users of your app may read; nobody writes through the public API.
-- The Edge Function writes with the service role key; RLS does not apply to it.
create policy "signed-in users can read tweets"
  on public.tweets for select
  to authenticated
  using (true);
03 — Section

Step 2: the Edge Function that calls the API and upserts

The function reads the newest stored created_at for its keyword, subtracts 60 seconds, and asks the API only for posts since then with the since_time: operator. The 60-second overlap is deliberate: posts indexed a little late are picked up on the next run, and the upsert turns the overlap into counter updates instead of duplicate rows.

Why since_time instead of deep paging. In our run the plain supabase query paged back 14.8 hours (320 posts over 17 requests) and then reported has_next_page: false. The endpoint docs warn that paging very deep with cursor on one broad query "is slow and can stop early". A scheduled job that only asks for the last few minutes never needs to page deep; a backfill splits the range into one-day windows (Step 5).

Counters are a snapshot. like_count and view_count are whatever the post had when it was fetched. Our sample had a median of 1 like and 58 views at fetch time, with 47.3% of posts at zero likes. Posts caught again by the overlap get fresher counters; if engagement matters, re-fetch older ids with /twitter/tweets (comma-separated tweet_ids) on a slower schedule.

Stay inside the limits. With MAX_PAGES = 10 one run handles 200 posts; our busiest hourly window held 50 posts and the busiest 5-minute window 15. JSON parsing of 10 pages is well under the 2-second CPU budget, and the network waits do not count toward it.

typescript
// supabase/functions/collect-tweets/index.ts
import { createClient } from "npm:@supabase/supabase-js@2";

const API = "https://api.twitterapi.io";
const KEYWORD = "supabase -filter:retweets";
const MAX_PAGES = 10; // 200 posts per run is plenty at ~400 posts a day

Deno.serve(async (req) => {
  // pg_cron sends this header; anything else is rejected
  if (req.headers.get("x-cron-secret") !== Deno.env.get("CRON_SECRET")) {
    return new Response("forbidden", { status: 403 });
  }
  const db = createClient(
    Deno.env.get("SUPABASE_URL")!,
    Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!, // server-side only, RLS does not apply
  );

  // Resume from the newest stored post, with 60 s of overlap the upsert absorbs
  const { data: last } = await db.from("tweets").select("created_at")
    .eq("keyword", KEYWORD).order("created_at", { ascending: false }).limit(1);
  const since = last?.length
    ? Math.floor(new Date(last[0].created_at).getTime() / 1000) - 60
    : Math.floor(Date.now() / 1000) - 3600; // first run: the last hour

  let cursor = "";
  let stored = 0;
  for (let page = 0; page < MAX_PAGES; page++) {
    const url = new URL(`${API}/twitter/tweet/advanced_search`);
    url.searchParams.set("query", `${KEYWORD} since_time:${since}`);
    url.searchParams.set("queryType", "Latest");
    url.searchParams.set("cursor", cursor);
    const res = await fetch(url, {
      headers: { "X-API-Key": Deno.env.get("TWITTERAPI_IO_KEY")! },
    });
    if (!res.ok) return new Response(`upstream ${res.status}`, { status: 502 });
    const body = await res.json();

    const rows = (body.tweets ?? []).map((t: any) => ({
      id: t.id,
      keyword: KEYWORD,
      created_at: new Date(t.createdAt).toISOString(), // "Mon Nov 30 23:10:07 +0000 2026"
      author_id: t.author?.id,
      author_username: t.author?.userName,
      text: t.text,
      lang: t.lang,
      like_count: t.likeCount,
      retweet_count: t.retweetCount,
      reply_count: t.replyCount,
      quote_count: t.quoteCount,
      view_count: t.viewCount,
      bookmark_count: t.bookmarkCount,
      conversation_id: t.conversationId,
      is_reply: t.isReply,
      raw: t, // drop this line to store about 6x less per row
    }));
    if (rows.length) {
      // same id again = update the counters, never a second row
      const { error } = await db.from("tweets").upsert(rows, { onConflict: "id" });
      if (error) return new Response(error.message, { status: 500 });
      stored += rows.length;
    }
    if (!body.has_next_page || !body.next_cursor) break;
    cursor = body.next_cursor;
  }
  return Response.json({ stored, since });
});
04 — Section

Step 3: deploy the function and set its secrets

Supabase's scheduling guide says a function called from pg_cron should have verify_jwt disabled, because the cron job does not carry a user's JWT. Turning JWT verification off makes the URL callable by anyone, so the function checks a shared secret header (x-cron-secret) and returns 403 without it.

Custom secrets are set with supabase secrets set NAME=value and read with Deno.env.get. SUPABASE_URL and the service role key are default secrets in hosted Edge Functions, so you only add your TwitterAPI.io key and the cron secret. The secrets page lists both the newer SUPABASE_SECRET_KEYS dictionary and the legacy SUPABASE_SERVICE_ROLE_KEY; the example uses the legacy name because it is a plain string.

bash
# supabase/config.toml: pg_cron calls without a user JWT
[functions.collect-tweets]
verify_jwt = false

# shell
supabase secrets set TWITTERAPI_IO_KEY=your_twitterapi_io_key CRON_SECRET=<same string as in Vault>
supabase functions deploy collect-tweets
05 — Section

Step 4: schedule it with pg_cron and pg_net

The job below follows the shape in Supabase's scheduling guide: secrets in Vault, cron.schedule with a name and a cron expression, and net.http_post reading the function URL from Vault. Supabase warns about one side effect: while the request is pending, pg_net writes the decrypted header value to net.http_request_queue, where any role that can log in to the database can read it. Use a secret that only opens this one function.

Which interval. We replayed the real timestamps from a continuous 14.8-hour window of the supabase keyword against four schedules and scaled the result to 30 days. Every check costs at least 15 credits ($0.00015), even when it finds nothing, so a short interval buys freshness with empty checks.

pg_cron intervalRequests a dayRuns that found nothingAPI cost / 30 days
every 1 min1,44173.1%$7.08
every 5 min28932.0%$2.76
every 15 min9913.3%$2.40
every hour390.0%$2.34

Five minutes is the sweet spot for a keyword of this size: 32.0% of runs come back empty and the bill is $2.76 against $1.84 for the posts alone. The hourly schedule is barely cheaper ($2.34) but needs up to three pages per run. A one-minute cron spends $7.08 for data that is no more than four minutes fresher.

sql
-- Extensions (Dashboard > Database > Extensions, or SQL)
create extension if not exists pg_cron;
create extension if not exists pg_net;

-- Keep the function URL and a shared secret in Vault, not in the job text
select vault.create_secret('https://your-project-ref.supabase.co/functions/v1/collect-tweets', 'collect_tweets_url');
select vault.create_secret('<long random string>', 'cron_secret');

-- Every 5 minutes: POST to the Edge Function
select cron.schedule(
  'collect-tweets-every-5-min',
  '*/5 * * * *',
  $$
  select net.http_post(
    url := (select decrypted_secret from vault.decrypted_secrets where name = 'collect_tweets_url'),
    headers := jsonb_build_object(
      'Content-Type', 'application/json',
      'x-cron-secret', (select decrypted_secret from vault.decrypted_secrets where name = 'cron_secret')
    ),
    body := jsonb_build_object('time', now())
  ) as request_id;
  $$
);

-- Did it run? pg_cron keeps the history here
select jobid, status, return_message, start_time
from cron.job_run_details
order by start_time desc
limit 10;
Bar chart of API cost per 30 days by pg_cron interval for one keyword: every minute $7.08, every 5 minutes $2.76, every 15 minutes $2.4, hourly $2.34, against $1.84 for the posts alone
Real post timestamps replayed against four pg_cron intervals, scaled to 30 days. Collected in 2026.
06 — Section

Step 5: backfill the last 7 days, one day window at a time

A new table starts empty. The Python script in the code section below fills the last seven days before the cron job takes over: one since_time:/until_time: window per UTC day, paging each window with next_cursor, and writing through Supabase's REST API with Prefer: resolution=merge-duplicates and on_conflict=id (PostgREST's upsert). Because it is an upsert, running the backfill after the cron job has started is harmless.

We used the same day-window method for the study. Without a Supabase project we could not store a week of rows, so instead we sampled the newest 160 posts of each of seven UTC days and measured the hours they spanned. That gives a posts-per-hour rate per day, which we scaled to 24 hours:

Day in the 7-day runPosts sampledHours they spanEstimated posts that day
Day 11609.89388
Day 21609.86390
Day 31609.37410
Day 41609.06424
Day 51607.84490
Day 616014.51265
Day 71607.81492

The estimates average 408 posts a day, so seven days stored would be about 2,856 rows. Each slice covers the last 8 to 15 hours of its day (the busier US daytime), so a full-day count is likely somewhat lower; size your PAGES_PER_DAY with headroom and let has_next_page end each window.

07 — Section

Step 6: SQL over the stored tweets

Once rows arrive, the point of using Postgres is that the analysis is plain SQL: hourly volume, the posts with the highest views, the language and reply mix, and fields pulled straight out of the raw jsonb column with -> and ->>. The last query tells you what the table really costs on disk, which is the number to watch against the plan's database limit.

For the supabase keyword the mix was 55.9% replies, 6.5% quotes, 16.2% with media and 23.3% with a link, from 1,113 distinct authors; 78.2% of posts were in English. If you only want original posts, add -filter:replies to the query instead of filtering after the fact, and you pay for fewer posts.

sql
-- Posts per hour for the last 7 days
select date_trunc('hour', created_at) as hour, count(*) as posts
from public.tweets
where keyword = 'supabase -filter:retweets'
  and created_at > now() - interval '7 days'
group by 1
order by 1;

-- Top 10 posts by views in the last 24 hours (counters as of the last upsert)
select author_username, left(text, 80) as text, view_count, like_count
from public.tweets
where created_at > now() - interval '24 hours'
order by view_count desc nulls last
limit 10;

-- Language mix and reply share
select lang,
       count(*) as posts,
       round(100.0 * avg(case when is_reply then 1 else 0 end), 1) as reply_pct
from public.tweets
group by lang
order by posts desc;

-- Pull a field that is not a column out of the raw jsonb
select id, raw -> 'author' ->> 'followers' as author_followers
from public.tweets
where raw ? 'quoted_tweet'
limit 20;

-- What the table costs you in storage today
select pg_size_pretty(pg_total_relation_size('public.tweets'));
08 — Section

What it costs: rows, megabytes and dollars

Storage and API spend are the two numbers that decide whether this stays on the Free plan. Row sizes are measured on the compact JSON text of each post before insert; Postgres on-disk size will differ, since jsonb has its own encoding, large values are compressed and moved to TOAST storage, and indexes add their own pages. Run the pg_total_relation_size query after a week for your real figure.

What you storeMedian bytes90th percentilePer 30 days at ~408 posts/day
Trimmed row (14 columns)4961,1098.9 MB
Full tweet JSON (raw jsonb)2,8508,82252.38 MB
Author object alone1,394n/a33.0% of the full JSON

At 408 posts a day the Free plan's 500 MB database lasts about 286 days with the raw JSON column and about 1,686 days without it. On Pro (from $25 a month) 8 GB of disk is included, then $0.125 per GB, per Supabase's pricing page. A 5-minute schedule is 288 invocations a day, about 8,640 a month, against 500,000 included on the Free plan. One catch: Supabase pauses Free projects after 1 week of inactivity.

The API side, for the same keyword over 30 days:

Same keyword, 30 daysRate cardCost
TwitterAPI.io, posts returned$0.15 per 1,000 posts$1.84
TwitterAPI.io, 5-minute pg_cron incl. empty checks15-credit minimum per request$2.76
Official X API pay-per-usage$0.005 per post read (docs.x.com)$61.20
Supabase Free plan500 MB database, 500,000 Edge Function invocations$0 (pauses after 1 week of inactivity)

Per post read, $0.005 on the official X API against $0.00015 here is about 33x. The X rate card also caps pay-per-usage at 3 million post reads a month. On TwitterAPI.io you buy credits ($1 = 100,000 credits, purchased credits never expire), new accounts that pass the automatic bot check get free starter credits (no card, one per person or network, expiring after 31 days), and the rate limit is 0.2 requests a second before the first payment and 20 a second after it; a 5-minute cron needs far less. Plan details are on the pricing page.

Dot plot of bytes per stored post: trimmed row median 496 and 90th percentile 1,109, full tweet JSON median 2,850 and 90th percentile 8,822
Bytes per stored post for 1,440 posts, measured on compact JSON text. Collected in 2026.
09 — Section

How we collected this

Question. If an Edge Function on a pg_cron schedule stored every new post for one keyword in Postgres, how many rows a day would it write, how large is each row, how many duplicates would an overlapping fetch produce, and what does each schedule cost?

Query and window. supabase -filter:retweets with queryType=Latest on /twitter/tweet/advanced_search, collected in 2026: one continuous pass back from the newest post (320 posts, 14.8 hours, until the cursor stopped), the newest 160 posts of each of seven UTC days through since_time:/until_time: windows, and a second short pass minutes after the first (40 posts, 36 of them already in the first pass).

Sample and cost. 1,440 unique posts from 75 requests, $0.22 of API credits. The analysis script, protocol and de-identified rows are in the repository under data/studies/twitter-api-supabase/.

What it cannot show. Daily totals are estimates from the latest 8 to 15 hours of each day, not complete counts. The schedule replay uses one 14.8-hour window. Row sizes are JSON text, not Postgres on-disk bytes. Another keyword can be ten times busier or quieter. And no Supabase project was involved: the Edge Function, cron job and SQL on this page were not deployed by us.

Privacy. Keyword results are mostly private individuals, so the raw pages were not kept in the repository; only aggregates and rows with no id, URL, text, author id or handle are published.

python
"""Backfill the last 7 days of one keyword into a Supabase table, then let pg_cron take over.

Runs anywhere with Python 3 + requests. Writes through Supabase's REST API (PostgREST) with an
upsert on the tweet id, so running it twice never creates duplicate rows.
"""
import os
import time
from datetime import datetime, timezone

import requests

API = "https://api.twitterapi.io"
HEADERS = {"X-API-Key": os.environ["TWITTERAPI_IO_KEY"]}
TABLE_URL = "https://your-project-ref.supabase.co/rest/v1/tweets?on_conflict=id"  # upsert key; your project ref here
SERVICE_KEY = os.environ["SUPABASE_SERVICE_ROLE_KEY"]  # server-side only
KEYWORD = "supabase -filter:retweets"
PAGES_PER_DAY = 30  # 600 posts per day window; raise it for busier keywords


def to_row(t):
    a = t.get("author") or {}
    created = datetime.strptime(t["createdAt"], "%a %b %d %H:%M:%S %z %Y")
    return {
        "id": t["id"], "keyword": KEYWORD, "created_at": created.isoformat(),
        "author_id": a.get("id"), "author_username": a.get("userName"),
        "text": t.get("text"), "lang": t.get("lang"),
        "like_count": t.get("likeCount"), "retweet_count": t.get("retweetCount"),
        "reply_count": t.get("replyCount"), "quote_count": t.get("quoteCount"),
        "view_count": t.get("viewCount"), "bookmark_count": t.get("bookmarkCount"),
        "conversation_id": t.get("conversationId"), "is_reply": t.get("isReply"),
        "raw": t,
    }


def upsert(rows):
    r = requests.post(
        TABLE_URL,
        headers={
            "apikey": SERVICE_KEY,
            "Authorization": f"Bearer {SERVICE_KEY}",
            "Content-Type": "application/json",
            "Prefer": "resolution=merge-duplicates,return=minimal",
        },
        json=rows,
        timeout=30,
    )
    r.raise_for_status()


def backfill_day(since, until):
    """One UTC day per query: deep paging on one broad query can stop early."""
    cursor, stored = "", 0
    for _ in range(PAGES_PER_DAY):
        r = requests.get(
            f"{API}/twitter/tweet/advanced_search",
            headers=HEADERS,
            params={"query": f"{KEYWORD} since_time:{since} until_time:{until}",
                    "queryType": "Latest", "cursor": cursor},
            timeout=30,
        )
        r.raise_for_status()
        body = r.json()
        tweets = body.get("tweets") or []
        if tweets:
            upsert([to_row(t) for t in tweets])
            stored += len(tweets)
        if not body.get("has_next_page") or not body.get("next_cursor"):
            break
        cursor = body["next_cursor"]
        time.sleep(0.2)  # fixed pacing, well under the paid rate limit
    return stored


if __name__ == "__main__":
    today = int(datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0).timestamp())
    for d in range(7, 0, -1):
        since, until = today - d * 86400, today - (d - 1) * 86400
        n = backfill_day(since, until)
        print(datetime.fromtimestamp(since, timezone.utc).date(), n, "posts stored")

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

10 — Questions

Questions readers ask

Can a Supabase Edge Function call the Twitter (X) API?

Yes. An Edge Function is Deno-compatible TypeScript with fetch, so it can call any HTTPS API. With TwitterAPI.io it sends a GET to /twitter/tweet/advanced_search (or a user timeline endpoint) with an X-API-Key header; no X developer account or OAuth flow is needed for reads. Keep the key in Edge Function secrets (supabase secrets set) and read it with Deno.env.get.

How do I run a Supabase function on a schedule?

Enable pg_cron and pg_net, store the project URL and a secret in Vault, then call cron.schedule('name', '*/5 * * * *', $$ select net.http_post(...) $$). Supabase's guide says the function should have verify_jwt disabled for this; protect it with your own secret header. Run history is in cron.job_run_details.

How do I avoid duplicate tweets in Supabase?

Make the X post id the primary key and write with upsert(rows, { onConflict: "id" }) (or PostgREST's on_conflict=id with Prefer: resolution=merge-duplicates). In our test a second pass minutes later returned 36 of 40 posts that were already stored; the upsert updated them instead of adding rows.

Do I need Row Level Security on the tweets table?

Yes, if the table is in the public schema. Supabase's docs say to enable RLS on every table in an exposed schema. Let only the Edge Function write (RLS does not apply to its service role key) and add a select policy for the roles that should read.

How much storage does a tweets table use?

In our sample a post took a median of 2,850 bytes as raw JSON and 496 bytes as 14 typed columns. At about 408 posts a day that is 52.38 MB or 8.9 MB per 30 days of JSON text; check the real on-disk size with pg_total_relation_size.

How often should pg_cron fetch new tweets?

For a keyword with a few hundred posts a day, every 5 to 15 minutes. Every check costs at least $0.00015, so in our replay a one-minute schedule cost $7.08 per 30 days (73% empty runs) against $2.76 for five minutes. If you need posts within seconds, use push delivery instead of polling.

Is the Supabase Free plan enough for storing tweets?

For one keyword of this size, yes: 500 MB of database lasts about 286 days with raw JSON, and a 5-minute cron uses about 8,640 of the 500,000 included Edge Function invocations a month. Free projects pause after 1 week of inactivity, which also stops the cron job.

11 — Further reading

Continue

Sources & further reading
More from this series

Writing about something you built with TwitterAPI.io? Our community rewards program pays API credits for honest tutorials, build logs and videos.

Build it

Stop reading. Start building.

Starter credits cover real testing on real data. Google sign-in, no card, no application queue.

Get an API key

Already building with TwitterAPI.io? Publish an honest tutorial or build log about it and earn up to $200 a month in API credits.