---
title: "Pagination and Batch Processing Patterns for High-Volume Tools"
date: "2026-11-28T11:35:00+07:00"
description: "Stop flooding the context: cap page sizes, switch from offset to cursor pagination, fan out bounded batches, and hand the model resumable state instead of raw row dumps."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/pagination-batch-processing-tools.jpg"
alt: "Abstract stacked layers representing paginated data records on a dark gradient"
tags: ['google-adk', 'adk-tools', 'pagination', 'batch-processing', 'async']
---

A tool that returns every matching row does not fail loudly — it fails expensively. Ten thousand rows arrive in one `FunctionResponse`, the context window swells, every later turn re-pays for them, and the model's attention collapses into the middle of a table it was never going to read. High-volume tools need a contract for *how much* they return, and a way for the model to ask for the rest.

This tutorial covers page-size caps, offset vs cursor pagination for tool backends, bounded fan-out batching, and how to make multi-page retrieval resumable inside an ADK session.

## Cap the payload before it reaches the model

Treat every tool return as a budget line. A 40 KB dump sets the cost floor for the entire rest of the conversation — see [token budgeting and cache-aware prompting](/blog/token-budgeting-cache-aware-prompting). The practical rules:

- **Default small**: page size 10–25 rows unless the caller asks otherwise.
- **Hard cap**: reject or clamp anything above ~100 rows in a single response.
- **Project columns**: return the five fields the model references, not `SELECT *`.
- **Always answer "is there more?"** with an explicit `has_more` flag and a cursor.

## Offset vs cursor pagination

The two standard strategies behave very differently when the underlying data moves:

| | Offset (`OFFSET n LIMIT m`) | Cursor / keyset |
|---|---|---|
| Request | `?offset=100&limit=25` | `?after=<opaque token>` |
| Cost of deep pages | Scans and discards `n` rows | Index lookup, constant-ish work |
| Rows inserted mid-scan | Duplicates or skipped rows | Stable snapshot of position |
| Guessability | Positions are arithmetic — trivial to enumerate | Token can be opaque (base64) |
| Fit for a tool | Simple, fine for shallow pages | Correct default for agents |

GraphQL's own guidance lands here: offset pagination has performance and security downsides on large sets, and once records shift between requests the offset maths become ambiguous; opaque cursors (base64-encoded, format not to be relied upon) are the stable model. SQL keyset pagination is the same idea at the driver level:

```sql
SELECT id, created_at, amount, state
FROM events
WHERE (created_at, id) > (?, ?)      -- last row of the previous page
ORDER BY created_at, id
LIMIT ?                               -- page size, clamped
```

This needs an index on `(created_at, id)` and a *total* order — ties on `created_at` alone make cursors unstable, which is why the key includes `id`.

## The cursor-carrying tool

The cursor is round-tripped through the model as an ordinary argument, while the expensive parts (the underlying query, a snapshot ID) stay in session state:

```python
PAGE_SIZE = 20          # default
MAX_PAGE_SIZE = 100     # hard clamp

def list_events(after: str | None = None, limit: int = PAGE_SIZE) -> dict:
    """List recent events, oldest-last, newest first.

    Args:
        after (str, optional): Opaque cursor from a previous call's
            'next_cursor'. Omit for the first page.
        limit (int, optional): Rows to fetch (1-100). Defaults to 20.

    Returns:
        dict: {'status', 'events', 'next_cursor', 'has_more', 'summary'}.
    """
    limit = max(1, min(limit, MAX_PAGE_SIZE))          # never trust the model
    created_at, row_id = decode_cursor(after) if after else ("", "")
    rows = fetch_page(created_at, row_id, limit + 1)    # fetch one extra
    has_more = len(rows) > limit
    page = rows[:limit]
    return {
        "status": "success",
        "events": [{k: r[k] for k in ("id", "created_at", "state")} for r in page],
        "next_cursor": encode_cursor(page[-1]) if has_more else None,
        "has_more": has_more,
        "summary": f"Returned {len(page)} events; "
                   + ("more available — pass next_cursor for the next page."
                      if has_more else "no further events."),
    }
```

Three deliberate choices: fetching `limit + 1` detects `has_more` without a second `COUNT(*)`; the clamp happens *inside* the tool because argument validation is not a privilege boundary; and the `summary` sentence tells the model whether to continue, so the loop decision is one token of reasoning rather than a row count.

## Fan-out batching: bounded, then aggregated

Some workloads are "do this for 50 things". Run them concurrently but under a semaphore, then return a *reduced* result — never 50 full responses:

```python
import asyncio

async def summarize_orders(order_ids: list[str]) -> dict:
    sem = asyncio.Semaphore(5)
    ids = order_ids[:20]                      # cap the fan-out too

    async def one(oid: str) -> dict:
        async with sem:
            return await fetch_order(oid)

    results = await asyncio.gather(*(one(i) for i in ids), return_exceptions=True)
    ok = [r for r in results if isinstance(r, dict)]
    failed = sum(1 for r in results if isinstance(r, Exception))
    return {
        "status": "partial" if failed else "success",
        "states": sorted({r["state"] for r in ok}),
        "total_value": round(sum(r["total"] for r in ok), 2),
        "failed_count": failed,
        "summary": f"Aggregated {len(ok)} of {len(ids)} orders "
                   f"({failed} failed); total {round(sum(r['total'] for r in ok), 2)}.",
    }
```

The tool returns a reduction — counts, sums, distinct states — plus a failure count, which is what the model needs to decide whether to retry the failures. `return_exceptions=True` keeps one slow API from failing the whole batch. Bounded concurrency also protects you from rate limits: unbounded `gather` on a 500-item list is a self-inflicted outage.

## When one turn cannot hold the result

Some retrievals are legitimately large — a nightly reconciliation, a 10k-row export. Do not solve that with a bigger page; change the execution model:

- **Checkpoint across turns.** Store `next_cursor` and partial aggregates under session state (`temp:` prefixes live for the current invocation only, so durable progress needs an unprefixed key), then let the model call again.
- **Delegate chunks to sub-agents.** A sub-agent consumes its pages and returns only an aggregate to the parent — the pattern behind [parallel tool calls](/blog/parallel-tool-calls-batching-ordering).
- **Use a long-running tool** when the work outlives the turn entirely; the runner pauses and resumes with progress updates, as in [pagination, timeouts, and long-running responses](/blog/pagination-timeouts-long-running-tool-responses).
- **Stop the loop explicitly.** Cap pages per invocation (say, five) and return `status: partial` with a note — an unbounded `while has_more` inside a tool is a denial-of-wallet bug.

## Takeaways

- Default page size 10–25, hard clamp around 100, project only the columns the model uses, and always report `has_more`.
- Prefer cursor/keyset pagination: offset degrades on deep pages and breaks when rows shift mid-scan; opaque cursors also stop the model from guessing positions.
- Fetch `limit + 1` rows to detect more data without an extra count query.
- Bound fan-out with a semaphore, cap the input list, use `return_exceptions=True`, and return an aggregate rather than raw responses.
- Make multi-page work resumable through session state or sub-agents; never let a tool loop over a whole table unbounded.

## Further reading

- [Pagination, timeouts, and long-running tool responses](/blog/pagination-timeouts-long-running-tool-responses)
- [Parallel tool calls: batching and ordering](/blog/parallel-tool-calls-batching-ordering)
- [Token budgeting and cache-aware prompting](/blog/token-budgeting-cache-aware-prompting)
- [Tool output formatting: Markdown vs structured dictionaries](/blog/tool-output-formatting-markdown-vs-json)
- [Database querying tools: safe read-only SQL agents](/blog/read-only-sql-agent-tools)
- [GraphQL pagination (connection model)](https://graphql.org/learn/pagination/)
- [ADK long-running function tools](https://adk.dev/tools-custom/function-tools/)
