This post uses the CocoIndex v1 API (@coco.fn, coco.App, coco.mount_each). If you used the v0 source connector API (SourceSpec, list() / get_value()), see the mapping from the v0 API. New to v1? Start with the CocoIndex v1 launch post. The code below matches the hn_trending_topics example on the CocoIndex main branch and runs on v1.1.0 or later.
Your data often lives behind an API that no connector covers: an internal REST service, a partner API, a public feed. A common case is context for an AI agent. An agent that answers from wikis, ticket systems and internal APIs needs an index that follows those systems as they change, and many of them offer only an endpoint you can poll. A polling script has to work out what is new, what changed and what was removed since the last poll, and keep a database in step with it.
A custom source moves that work to CocoIndex. In CocoIndex v1 it needs no connector API: it is ordinary async Python that fetches data, plus processing components that declare the rows that should exist downstream. You describe the target as a function of the source, and CocoIndex works out the inserts, updates and deletes.
This post builds one over Hacker News. It fetches recent stories and their nested comments through the Algolia HN API and keeps two Postgres tables in sync: one row per message and one row per topic mention. The code is the hn_trending_topics example in the CocoIndex repo. The pipeline also extracts topics with an LLM and ranks them; that half has its own post, Normalize and rank Hacker News topics with an LLM. This post covers the source side: the fetch functions, the rows each component owns, what a failed fetch does, and what a second run changes.
- The source pattern: two
async deffetch functions and one component per item, with no connector class (Fetch from the Hacker News API). - Declared rows: how a component owns its rows, and why primary keys must be stable (Process each thread).
- Failures: why one failed HTTP request does not touch the other threads’ rows (When a fetch fails).
- Reruns: what a second
cocoindex updatefetches, which LLM calls it skips, and which rows it deletes, with a simulator you can step through (What a second run does). - Inspection: how to see which component owns each row (Inspect what each component owns).
What a source needs: 4 parts
Pipelines often read from systems that are not clean tables. Internal REST services and partner APIs return pages of JSON, legacy systems need their own client, and some data models do not fit any existing connector. In CocoIndex you fetch that data with plain async def functions, run each item as its own processing component, and let the component declare the target rows it owns. CocoIndex then detects what changed, syncs the target, and deletes the rows of an item that has left the source.
The source has to provide 4 things, and most APIs you can poll already do:
- A list of the current keys. One call that says which items exist now. Here it is the 10 newest story IDs. An item that is not in the list is treated as gone.
- A fetch by key. One call that returns the full item for a key. Here it is a story with its comments.
- One component per key.
coco.mount_eachstarts a processing component per key; the key names the component on every run. - Stable primary keys on the rows. The rows a component declares need IDs that do not change between runs. Hacker News IDs never change.
The pipeline
The example does five things:
- Call the Hacker News search API for recent stories
- Fetch the nested comments of each story
- Extract topics from every message with an LLM
- Store messages and topics in Postgres
- Search the stored messages by topic
The code has three parts:
- Two async functions over the Algolia HN API
fetch_thread_listlists recent story IDsfetch_threadpulls one story with its full comment tree
- One processing component per thread
process_threadextracts topics from the story and every comment- It declares rows into two Postgres tables (
hn_messages,hn_topics)
- Query helpers
- Rank trending topics in SQL
- Search messages by topic
Prerequisites
- Postgres running locally. The CocoIndex repo ships a compose file:
docker compose -f dev/postgres.yaml up -dfrom the repo root. The example reads the connection string fromPOSTGRES_URLand defaults topostgres://cocoindex:cocoindex@localhost/cocoindex. - An LLM API key. The default model is
gemini/gemini-2.5-flashthrough litellm; setGEMINI_API_KEY, or setLLM_MODELto any litellm model id and the matching provider key. The example’s.env.examplelists both variables: fromexamples/hn_trending_topics, runcp .env.example .envand fill it in. - Python 3.11 or later (
requires-pythonin the example’spyproject.toml).
Define the data models
Everything the pipeline handles is a plain dataclass. Thread and Comment model what we read from the API:
@dataclass
class Comment:
id: str
author: str | None
text: str | None
created_at: datetime | None
@dataclass
class Thread:
id: str
author: str | None
text: str
url: str | None
created_at: datetime | None
comments: list[Comment]
Each source item is one thread: a story plus all of its comments. Hacker News returns comments as a reply tree; the parser flattens it into a single list.
HnMessage and HnTopic are the schemas of the two target tables:
@dataclass
class HnMessage:
"""Schema for hn_messages table."""
id: str
thread_id: str
content_type: str
author: str | None
text: str | None
url: str | None
created_at: datetime | None
@dataclass
class HnTopic:
"""Schema for hn_topics table."""
topic: str
message_id: str
thread_id: str
content_type: str
created_at: datetime | None
A thread and each of its comments both become an HnMessage row, told apart by content_type. Every extracted topic becomes an HnTopic row keyed on (topic, message_id). A topic mentioned in 30 messages has 30 rows, and the ranking query sums a weight over those rows.
A primary key is the identity of a row. It must stay the same across runs: CocoIndex matches this run’s rows to the last run’s rows by key, so a stable key updates a row in place, and a key that changes on every run deletes the row and inserts a copy. Here the keys are Hacker News IDs, which never change.
Fetch from the Hacker News API
The source is two small async functions over the Algolia HN API.
Listing recent threads
fetch_thread_list returns the most recent story IDs. This list decides which threads the index holds on this run:
async def fetch_thread_list(
session: aiohttp.ClientSession, max_results: int = MAX_THREADS
) -> list[str]:
"""Fetch list of recent thread IDs from HackerNews."""
search_url = "https://hn.algolia.com/api/v1/search_by_date"
params: dict[str, str | int] = {"tags": "story", "hitsPerPage": max_results}
async with session.get(search_url, params=params) as response:
response.raise_for_status()
data = await response.json()
thread_ids = [
hit["objectID"] for hit in data.get("hits", []) if hit.get("objectID")
]
return thread_ids
Fetching a full thread
fetch_thread pulls one story with all its comments and parses the raw JSON into a Thread. The inner parse_comments walks the reply tree recursively and flattens it. The story title and body become the thread text:
async def fetch_thread(session: aiohttp.ClientSession, thread_id: str) -> Thread:
"""Fetch a single thread with all its comments."""
item_url = f"https://hn.algolia.com/api/v1/items/{thread_id}"
async with session.get(item_url) as response:
response.raise_for_status()
data = await response.json()
comments: list[Comment] = []
# Parse comments recursively
def parse_comments(parent: dict[str, Any]) -> None:
for child in parent.get("children", []):
if comment_id := child.get("id"):
ctime = child.get("created_at")
comments.append(
Comment(
id=str(comment_id),
author=child.get("author"),
text=child.get("text"),
created_at=datetime.fromisoformat(ctime) if ctime else None,
)
)
parse_comments(child)
parse_comments(data)
ctime = data.get("created_at")
text = data.get("title", "")
if more_text := data.get("text"):
text += "\n\n" + more_text
return Thread(
id=thread_id,
author=data.get("author"),
text=text,
url=data.get("url"),
created_at=datetime.fromisoformat(ctime) if ctime else None,
comments=comments,
)
Any HTTP API or third-party SDK that you can poll can be a source in the same way: fetch the data in plain Python and pass it to the pipeline.
What you see. For one story with 40 comments, fetch_thread returns one Thread whose comments list has 40 entries, in depth-first order, whatever their nesting.
Extract topics with a memoized LLM call
process_thread sends the text of the story and of each comment to extract_topics, a CocoIndex function that calls an LLM and returns a list of topic strings. For the source side, only its decorator matters, because it decides what a rerun costs:
@coco.fn(
memo=True,
deps={"model": LLM_MODEL, "prompt": TopicsResponse.model_fields["topics"].description},
)
async def extract_topics(text: str | None) -> list[str]:
...
memo=Truecaches the result per input text. When a message’s text is unchanged, CocoIndex returns the cached topics and does not call the LLM. Without it, every run sends every message to the model again. See memoization.depslists values the function depends on that are not in its body. The model id is a module constant, and the prompt is inmodels.py. Withoutdeps, editing either one would not invalidate the cache, and old topics would stay. Seedeps.
The prompt (it asks for one canonical name per topic) and the weighted SQL score that ranks the topics are in the companion post, Normalize and rank Hacker News topics with an LLM.
Process each thread
Each thread runs as its own processing component. process_thread fetches the thread, extracts topics for the story and every comment, and declares the resulting rows:
@coco.fn
async def process_thread(
thread_id: str,
targets: TableTargets,
) -> None:
"""Fetch and process a single thread and its comments."""
async with aiohttp.ClientSession() as session:
thread = await fetch_thread(session, thread_id)
thread_topics = await extract_topics(thread.text)
# Declare thread message row
targets.messages.declare_row(
row=HnMessage(
id=thread.id,
thread_id=thread.id,
content_type="thread",
author=thread.author,
text=thread.text,
url=thread.url,
created_at=thread.created_at,
),
)
# Declare thread topic rows
for topic in thread_topics:
targets.topics.declare_row(
row=HnTopic(
topic=topic,
message_id=thread.id,
thread_id=thread.id,
content_type="thread",
created_at=thread.created_at,
),
)
# Process comments
for comment in thread.comments:
comment_topics = await extract_topics(comment.text)
# Declare comment message row
targets.messages.declare_row(
row=HnMessage(
id=comment.id,
thread_id=thread.id,
content_type="comment",
author=comment.author,
text=comment.text,
url="",
created_at=comment.created_at,
),
)
# Declare comment topic rows
for topic in comment_topics:
targets.topics.declare_row(
row=HnTopic(
topic=topic,
message_id=comment.id,
thread_id=thread.id,
content_type="comment",
created_at=comment.created_at,
),
)
declare_row states that a row should exist; the code has no inserts or deletes. When the component finishes, CocoIndex compares the rows it declared with the rows the same component declared on the previous run. It then applies only the creates, updates and deletes needed to match. A row the component no longer declares, such as a topic the LLM stopped returning, is deleted.
Why one component per thread? A component groups one thread’s work with the rows it owns. Components run independently and in parallel. When a component finishes, it commits: CocoIndex writes that thread’s row changes to Postgres without waiting for the other threads.
Ownership keeps deletes safe. CocoIndex never compares the whole table with the API. It compares each component’s rows with the rows that same component declared last time, so a component can delete only rows it declared itself.
When a fetch fails
fetch_thread calls response.raise_for_status(), so an HTTP error from the API raises inside process_thread. mount_each runs each component in the background: a failure in one component is logged, and the other components continue.
A component declares its rows in memory and writes them only after its body returns, so a component that raises has written nothing on that run. Its rows from the last successful run stay in Postgres, and if the story is still among the 10 latest, the next cocoindex update fetches it again. You do not need a retry loop for the index to stay consistent. To be alerted when a component fails, install an exception handler.
Quick check: the API stops returning a comment that it returned on the last run. What happens to its rows?
The Thread from fetch_thread no longer contains that comment, so process_thread does not declare its HnMessage row or its HnTopic rows. CocoIndex deletes them when the component commits. No code handles deletion.
Wire up the app
The Postgres pool is created once in the app lifespan and referenced by a context key. @coco.lifespan runs once when the CocoIndex runtime starts (for cocoindex update, once around the run), and builder.provide makes the pool available to every component under the key PG_DB:
PG_DB = coco.ContextKey[asyncpg.Pool]("hn_db")
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
builder.settings.db_path = pathlib.Path("./cocoindex.db")
async with asyncpg.create_pool(DATABASE_URL) as pool:
builder.provide(PG_DB, pool)
yield
db_path is where CocoIndex keeps its own state between runs, including the memoized LLM results.
app_main mounts the two table targets, fetches the recent thread IDs, and starts one process_thread component per thread with coco.mount_each:
@dataclass
class TableTargets:
"""Container for table targets."""
messages: postgres.TableTarget[HnMessage]
topics: postgres.TableTarget[HnTopic]
@coco.fn
async def app_main() -> None:
"""Main pipeline function."""
# Set up table targets
messages_table = await postgres.mount_table_target(
PG_DB,
table_name="hn_messages",
table_schema=await postgres.TableSchema.from_class(
HnMessage, primary_key=["id"]
),
pg_schema_name="coco_examples",
)
topics_table = await postgres.mount_table_target(
PG_DB,
table_name="hn_topics",
table_schema=await postgres.TableSchema.from_class(
HnTopic, primary_key=["topic", "message_id"]
),
pg_schema_name="coco_examples",
)
targets = TableTargets(messages=messages_table, topics=topics_table)
# Fetch thread IDs from HackerNews
async with aiohttp.ClientSession() as session:
thread_ids = await fetch_thread_list(session)
# Process threads (each component fetches its own thread data)
await coco.mount_each(process_thread, ((tid, tid) for tid in thread_ids), targets)
app = coco.App(
coco.AppConfig(name="HNTrendingTopics"),
app_main,
)
mount_each takes one (key, value) pair per item and passes the value as the first argument of process_thread; targets is passed to every component. Here the key and the value are both the thread ID. The key sets the component path, which is the name under which CocoIndex tracks a component’s rows between runs, so each thread keeps the same path on every run. TableSchema.from_class derives the SQL columns from the dataclasses. The app is plain Python; the CocoIndex engine, written in Rust, does the incremental sync.
Run it
Install the project in editable mode from the example directory:
pip install -e .
Then build the index:
cocoindex update main
main is the Python module (main.py) that defines app. The run fetches the 10 most recent stories (MAX_THREADS in main.py), extracts topics from every message, and writes coco_examples.hn_messages and coco_examples.hn_topics. Each cocoindex update is one catch-up run that syncs the tables to the current feed and exits.
What you see. After the first run, hn_messages has one row per story and per comment of those 10 stories, and hn_topics has one row per (topic, message) pair.
Inspect what each component owns
CocoIndex records every row it wrote together with the component that declared it. Two commands read that record from the CLI:
cocoindex show main # stable paths, incl. one per thread
cocoindex show main --target-states # every tracked row, with its owner component
What you see. cocoindex show main lists the app’s stable paths, including one per story ID under process_thread from the last run. With --target-states, each hn_messages and hn_topics row appears with the component that owns it, so you can tell which story put a row there. Add --tree to nest the rows under their tables.
What a second run does
Run cocoindex update main again a few minutes later. The feed has moved: some stories are new, some have new comments, and the oldest have left the 10 most recent.
- A new story gets a new component. Every message in it is new text, so each one goes to the LLM.
- A story with new comments is fetched again over HTTP. Only new or edited comments are cache misses in
extract_topics; the other messages reuse their cached topics. - An unchanged story is fetched again, and every
extract_topicscall is a cache hit. Its rows do not change. - A story that left the 10 most recent has no component on this run. CocoIndex deletes the
hn_messagesandhn_topicsrows that its component owned.
The last point means the tables hold only the stories in the current window. To cover more stories, raise MAX_THREADS.
The simulator below applies these rules to a 10-story window. Each click is one cocoindex update main: one story enters, the oldest leaves, and one story gets a comment. To see a failed fetch, turn on the toggle before a run. That story keeps its rows from the last run while the other 9 components commit, and the next run without the toggle picks up the comment it missed.
Poll the feed, watch what each component owns
Illustrative stories and countsNext run: S11 is posted, S6 gets a comment, and S1 falls out of the 10 newest.
- run
- 1
- LLM calls
- 37
- rows added
- 110
- rows deleted
- 0
Run 1: every story is new, so every message goes to the LLM: 37 calls. 11 HTTP requests (1 list, 10 stories).
- S10Reading the Linux scheduler source owns 4 message rows and 8 topic rows new · 12 rows added 4 LLM calls
- S9Ask HN: What do you self-host? owns 5 message rows and 5 topic rows new · 10 rows added 5 LLM calls
- S8Notes on writing a B-tree from scratch owns 2 message rows and 6 topic rows new · 8 rows added 2 LLM calls
- S7Show HN: A terminal UI for Kafka topics owns 3 message rows and 6 topic rows new · 9 rows added 3 LLM calls
- S6Why our build cache missed every time owns 4 message rows and 4 topic rows new · 8 rows added 4 LLM calls
- S5A tiny HTTP server in 300 lines of C owns 5 message rows and 15 topic rows new · 20 rows added 5 LLM calls
- S4Postgres as a job queue, two years in owns 2 message rows and 4 topic rows new · 6 rows added 2 LLM calls
- S3Ask HN: How do you test data pipelines? owns 3 message rows and 3 topic rows new · 6 rows added 3 LLM calls
- S2SQLite as an application file format owns 4 message rows and 12 topic rows new · 16 rows added 4 LLM calls
- S1A profiler for async Rust owns 5 message rows and 10 topic rows new · 15 rows added 5 LLM calls
- No story has left the 10 newest yet.
If you change the prompt or set a different LLM_MODEL, the deps on extract_topics change, every cached result is invalid, and the next run extracts topics again for every non-empty message. No manual migration is needed.
To see what a run would change before it writes anything, add --preview: cocoindex update main --preview computes the target actions and prints the planned actions without applying them. It still runs every component, so it makes the HTTP fetches and the LLM calls for cache misses.
Quick check: why is fetch_thread called on every run, but the LLM is not?
process_thread is not memoized, so its body runs for every thread on every run, and the body calls fetch_thread. Only extract_topics has memo=True, and its cache key is the message text plus its logic and deps. A single HTTP request per thread is cheap; an LLM call per message is not.
Query the tables
The index is two plain Postgres tables, so any library or framework can query them. The example ships two query helpers over asyncpg: get_trending_topics ranks topics with a weighted SQL score, and search_by_topic joins hn_topics to hn_messages to return the messages behind a topic. Both queries, and how the weights change the ranking, are in the companion post under Rank topics with a weighted SQL score.
Run both from the command line. cocoindex update loads .env for you; python main.py reads POSTGRES_URL before it loads .env, so export the variable in your shell if you changed it from the default:
python main.py # top 20 trending topics + interactive search
python main.py "rust" # search content for one topic
What to try next
- Add an LLM summary of each thread as a third table.
- Add embeddings and vector search over
hn_messages. - Raise
MAX_THREADS, or list stories with a different Algolia query (for exampletags=show_hn). - Add another news source (Reddit, Lobsters) as two more fetch functions and its own component.
- Make the source live.
mount_eachalso accepts aLiveMapView, which can scan the current items and watch for changes; run withcocoindex update main --live, andmount_eachadds, updates and removes components as the source changes. See live components. - Force everything to run again with
cocoindex update main --full-reprocess. It bypasses every memoization cache, so every non-empty message goes to the LLM again.
Each of these adds rows that a component declares; the incremental behavior stays the same.
Other APIs that fit the pattern
The same pattern fits other data that has no standard connector, has deep nesting, or needs heavy processing first. Agent context from wikis and ticket systems is the case in the introduction; here are three more.
One row from several services
User data is often split across services. A component can join them before the data reaches the index. For example, a component:
- Fetches a user ID from an auth service (Okta, Auth0)
- Uses that ID to fetch billing status from the Stripe API
- Uses that ID to fetch usage logs from an internal Redis
The component declares a single User360 row, so there is no join to manage downstream. When the user upgrades in Stripe or changes their email in Auth0, the next run updates that row.
A SQL view of a legacy system
Some data is in systems that are hard to query (SOAP, XML, mainframes). Wrap the legacy read path in a fetch function, and the CocoIndex target gives you a SQL table over it, with no change to the legacy system.
Monitoring public data
Some public websites and APIs offer no webhooks: competitor pricing pages, regulatory feeds, market data APIs. Because CocoIndex compares declared rows with the previous run, the downstream tables change only when the data changes, and a poll that returns the same data writes no rows to the target.
Source
The full example is examples/hn_trending_topics in the CocoIndex repo.
Frequently asked questions
How do I turn a polling API like Hacker News into a CocoIndex source?
In CocoIndex v1 a custom source needs no connector API. Write plain async def functions over the API (fetch_thread_list lists recent story IDs, fetch_thread pulls one story with its flattened comment tree), then start one processing component per item with coco.mount_each. Each component declares the Postgres rows it owns, and CocoIndex compares them with the previous run and applies the changes.
What does an API need to provide to be a custom source?
4 things: a call that lists the keys of the items that exist now, a call that fetches one item by key, one processing component per key (coco.mount_each), and rows with primary keys that stay the same between runs. Most APIs you can poll already provide the first two, and the rest is plain Python.
How do I model the data for a custom source?
Everything is a plain dataclass: Thread and Comment model what you read from the API, and HnMessage and HnTopic are the target table schemas. A primary key is the identity of a row and must stay the same across runs, so a rerun updates rows in place instead of deleting and inserting them.
What happens when one fetch from the API fails?
The HTTP error raises inside that story's process_thread component. A component writes its rows only after its body returns, so the failed component writes nothing on that run and its rows from the last successful run stay in Postgres. mount_each logs the failure and the other components continue. The next cocoindex update fetches the story again if it is still listed.
See When a fetch fails.
Does a rerun call the LLM again for every message?
Not if extract_topics is decorated with @coco.fn(memo=True). Then a message whose text is unchanged is a cache hit and the LLM is not called; only new or edited messages are. Each thread is still fetched again over HTTP, because process_thread is not memoized. Pass the model id and the prompt in deps, so that changing either one invalidates the cache. A story that leaves the latest MAX_THREADS stories has its rows deleted, so the tables cover the current feed, not an archive.
How do I run the Hacker News pipeline?
Start Postgres, set POSTGRES_URL if you don't use the default, set an LLM key (GEMINI_API_KEY by default), install the example with pip install -e ., then run cocoindex update main. Each run syncs the tables to the 10 most recent stories and exits; run it again to catch up. python main.py prints the top trending topics and searches messages by topic.
See Run it.
What else can I build with CocoIndex custom sources?
The pattern fits data that has no standard connector: context for an AI agent from wikis and ticket systems, one row joined from several services, a SQL table over a legacy SOAP or XML system, and monitors of public data whose tables change only when the data changes.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.


