Turn a polling API into an incremental source: Hacker News

Turn a polling API into an incremental CocoIndex v1 source in plain Python, using Hacker News: list keys, fetch by key, own rows, survive failed fetches.

TutorialUpdated 14 min read
Turn a polling API into an incremental source: Hacker News. A card says mount_each starts 1 component per story for the 10 newest stories; an arrow points to 3 illustrative stories: S1 and S2, each a component that owns its rows, and S4, new, outlined in green, whose component and rows are added.
Enlarge cover

Turn a polling API into an incremental source: Hacker News

Zoom in to see details.

Turn a polling API into an incremental source: Hacker News. A card says mount_each starts 1 component per story for the 10 newest stories; an arrow points to 3 illustrative stories: S1 and S2, each a component that owns its rows, and S4, new, outlined in green, whose component and rows are added.
Updated for CocoIndex v1

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.

What you learn

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 custom source needs 4 parts, and plain Python provides them. A list of the current item keys: fetch_thread_list in this example; CocoIndex then deletes the rows of a key that is no longer listed. A fetch for one item by key: fetch_thread(session, id), which runs inside that item's component. One component per key: coco.mount_each, which tracks each component by its key. Rows with stable primary keys: declare_row with HackerNews IDs, so CocoIndex writes only the rows that changed. A note says there is no connector class: the source is plain async Python, and the same 4 parts fit any API you can list and fetch.
The custom-source patternEnlarge

The custom-source pattern

Zoom in to see details.

A custom source needs 4 parts, and plain Python provides them. A list of the current item keys: fetch_thread_list in this example; CocoIndex then deletes the rows of a key that is no longer listed. A fetch for one item by key: fetch_thread(session, id), which runs inside that item's component. One component per key: coco.mount_each, which tracks each component by its key. Rows with stable primary keys: declare_row with HackerNews IDs, so CocoIndex writes only the rows that changed. A note says there is no connector class: the source is plain async Python, and the same 4 parts fit any API you can list and fetch.
  • 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_each starts 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:

  1. Call the Hacker News search API for recent stories
  2. Fetch the nested comments of each story
  3. Extract topics from every message with an LLM
  4. Store messages and topics in Postgres
  5. Search the stored messages by topic
fetch_thread_list lists recent story IDs from the HackerNews API; mount_each mounts one process_thread component per thread ID; each component calls fetch_thread, runs extract_topics on every message, and declares rows into the hn_messages and hn_topics tables in the coco_examples Postgres schema.
The indexing flowEnlarge

The indexing flow

Zoom in to see details.

fetch_thread_list lists recent story IDs from the HackerNews API; mount_each mounts one process_thread component per thread ID; each component calls fetch_thread, runs extract_topics on every message, and declares rows into the hn_messages and hn_topics tables in the coco_examples Postgres schema.

The code has three parts:

  1. Two async functions over the Algolia HN API
    • fetch_thread_list lists recent story IDs
    • fetch_thread pulls one story with its full comment tree
  2. One processing component per thread
    • process_thread extracts topics from the story and every comment
    • It declares rows into two Postgres tables (hn_messages, hn_topics)
  3. 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 -d from the repo root. The example reads the connection string from POSTGRES_URL and defaults to postgres://cocoindex:cocoindex@localhost/cocoindex.
  • An LLM API key. The default model is gemini/gemini-2.5-flash through litellm; set GEMINI_API_KEY, or set LLM_MODEL to any litellm model id and the matching provider key. The example’s .env.example lists both variables: from examples/hn_trending_topics, run cp .env.example .env and fill it in.
  • Python 3.11 or later (requires-python in the example’s pyproject.toml).

Define the data models

Everything the pipeline handles is a plain dataclass. Thread and Comment model what we read from the API:

main.py
@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.

A HackerNews item nests its comments as children; parse_comments walks the tree depth-first and fetch_thread returns one Thread holding the story text and a flat comments list.
Thread parsingEnlarge

Thread parsing

Zoom in to see details.

A HackerNews item nests its comments as children; parse_comments walks the tree depth-first and fetch_thread returns one Thread holding the story text and a flat comments list.

HnMessage and HnTopic are the schemas of the two target tables:

main.py
@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.

The HnMessage and HnTopic dataclasses define the coco_examples.hn_messages and hn_topics tables; declare_row writes one hn_messages row per story or comment, keyed by id, and one hn_topics row per topic in a message, keyed by (topic, message_id).
The data schemaEnlarge

The data schema

Zoom in to see details.

The HnMessage and HnTopic dataclasses define the coco_examples.hn_messages and hn_topics tables; declare_row writes one hn_messages row per story or comment, keyed by id, and one hn_topics row per topic in a message, keyed by (topic, message_id).

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:

main.py
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:

main.py
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:

main.py
@coco.fn(
    memo=True,
    deps={"model": LLM_MODEL, "prompt": TopicsResponse.model_fields["topics"].description},
)
async def extract_topics(text: str | None) -> list[str]:
    ...
  • memo=True caches 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.
  • deps lists values the function depends on that are not in its body. The model id is a module constant, and the prompt is in models.py. Without deps, editing either one would not invalidate the cache, and old topics would stay. See deps.

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:

main.py
@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.

Row ownership, with illustrative IDs and topics. The process_thread component for key S1 owns the hn_messages rows S1, C1, C2, C3 and C4 and the hn_topics rows (CocoIndex, S1), (PostgreSQL, C1) and (PostgreSQL, C2). The component for key S2 owns the hn_messages rows S2 and C5 and the hn_topics rows (Rust, S2) and (LLM, C5). The command cocoindex show main --target-states lists each tracked row with the component that owns it. A note says that when S1 is no longer listed, its component is not mounted, and CocoIndex deletes the rows in its box.
Row ownershipEnlarge

Row ownership

Zoom in to see details.

Row ownership, with illustrative IDs and topics. The process_thread component for key S1 owns the hn_messages rows S1, C1, C2, C3 and C4 and the hn_topics rows (CocoIndex, S1), (PostgreSQL, C1) and (PostgreSQL, C2). The component for key S2 owns the hn_messages rows S2 and C5 and the hn_topics rows (Rust, S2) and (LLM, C5). The command cocoindex show main --target-states lists each tracked row with the component that owns it. A note says that when S1 is no longer listed, its component is not mounted, and CocoIndex deletes the rows in its box.

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.

An illustrative run with 3 components. For S1 and S3, fetch_thread, extract_topics and declare_row succeed and the rows are committed. For S2, fetch_thread raises, outlined in red; extract_topics and declare_row are skipped, shown dashed, the error is logged and no rows are written, so the rows from the last run are kept. A note says a component only declares rows in memory, so a failure leaves nothing half-written; its rows from the last successful run stay as they were, and the next cocoindex update fetches S2 again if it is still listed.
A failed fetchEnlarge

A failed fetch

Zoom in to see details.

An illustrative run with 3 components. For S1 and S3, fetch_thread, extract_topics and declare_row succeed and the rows are committed. For S2, fetch_thread raises, outlined in red; extract_topics and declare_row are skipped, shown dashed, the error is logged and no rows are written, so the rows from the last run are kept. A note says a component only declares rows in memory, so a failure leaves nothing half-written; its rows from the last successful run stay as they were, and the next cocoindex update fetches S2 again if it is still listed.

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:

main.py
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:

main.py
@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:

sh
pip install -e .

Then build the index:

sh
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:

sh
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.

Illustrative stories. A second cocoindex update: run 1 listed stories S1, S2 and S3; run 2 lists S2, S3 and S4. S1, outlined in red, is not listed, so its component and its hn_messages and hn_topics rows are deleted. S2 has one new comment, c3: its other messages are cache hits and only c3 calls the LLM. S3 is unchanged and makes no LLM call. S4 is new: every message calls the LLM and its rows are added.
Second runEnlarge

Second run

Zoom in to see details.

Illustrative stories. A second cocoindex update: run 1 listed stories S1, S2 and S3; run 2 lists S2, S3 and S4. S1, outlined in red, is not listed, so its component and its hn_messages and hn_topics rows are deleted. S2 has one new comment, c3: its other messages are cache hits and only c3 calls the LLM. S3 is unchanged and makes no LLM call. S4 is new: every message calls the LLM and its rows are added.
  • 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_topics call 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_messages and hn_topics rows 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 counts

Next 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).

  1. S10Reading the Linux scheduler source owns 4 message rows and 8 topic rows new · 12 rows added 4 LLM calls
  2. S9Ask HN: What do you self-host? owns 5 message rows and 5 topic rows new · 10 rows added 5 LLM calls
  3. S8Notes on writing a B-tree from scratch owns 2 message rows and 6 topic rows new · 8 rows added 2 LLM calls
  4. S7Show HN: A terminal UI for Kafka topics owns 3 message rows and 6 topic rows new · 9 rows added 3 LLM calls
  5. S6Why our build cache missed every time owns 4 message rows and 4 topic rows new · 8 rows added 4 LLM calls
  6. S5A tiny HTTP server in 300 lines of C owns 5 message rows and 15 topic rows new · 20 rows added 5 LLM calls
  7. S4Postgres as a job queue, two years in owns 2 message rows and 4 topic rows new · 6 rows added 2 LLM calls
  8. S3Ask HN: How do you test data pipelines? owns 3 message rows and 3 topic rows new · 6 rows added 3 LLM calls
  9. S2SQLite as an application file format owns 4 message rows and 12 topic rows new · 16 rows added 4 LLM calls
  10. S1A profiler for async Rust owns 5 message rows and 10 topic rows new · 15 rows added 5 LLM calls
  11. 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:

sh
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 example tags=show_hn).
  • Add another news source (Reddit, Lobsters) as two more fetch functions and its own component.
  • Make the source live. mount_each also accepts a LiveMapView, which can scan the current items and watch for changes; run with cocoindex update main --live, and mount_each adds, 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:

  1. Fetches a user ID from an auth service (Okta, Auth0)
  2. Uses that ID to fetch billing status from the Stripe API
  3. 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.

See Fetch from the Hacker News API.

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.

See What a source needs: 4 parts.

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.

See Define the data models.

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.

See What a second run does.

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.

See Other APIs that fit the pattern.

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.