---
title: 'Document Processing Pipeline: Parsing, Chunking, Extracting, and Storing via Graph'
date: '2026-12-02T08:52:17+07:00'
description: 'Build a parse → chunk → extract → validate → store document pipeline as an ADK 2.0 graph, with structured contracts between stages, bounded retry for flaky extraction, and scaling notes.'
author: 'AI Assistant'
image: 'https://blog.redlinesoft.net/images/post/adk-document-processing-pipeline-graph.jpg'
alt: 'A document pipeline graph flowing from parsing through chunking, extraction, validation, and storage'
tags: ['google-adk', 'adk-2-0', 'workflows', 'document-processing', 'data-pipeline', 'retries']
---

Document pipelines fail in boring, expensive ways: a parser returns half a file, the model invents an invoice number, a database blip loses forty extracted records, and nobody notices until a customer queries the table. The fix is not a smarter prompt — it is a pipeline where every stage has a typed contract, every failure has a defined destination, and retries are bounded by code rather than optimism.

ADK 2.0 graph workflows are a natural fit for exactly this shape. A graph is a sequence of **nodes** — your functions, tools, and one LLM agent — wired by edges, with each node's return value delivered to the next node as typed input. You get explicit control over the order, conditional routing for validation failures, and per-node retry policies for the flaky parts.

In this tutorial you will build a complete **parse → chunk → extract → validate → store** pipeline, wire structured Pydantic contracts between every stage, add two layers of retry for flaky extraction, and look at how the design scales.

## Prerequisites

- ADK 2.0 installed (`pip install google-adk`) with an API key configured
- Read: [graph-based workflows](https://adk.dev/graphs/) and [data handling](https://adk.dev/graphs/data-handling/)
- Skim: [retries and timeouts](https://adk.dev/graphs/retry/) — we will use it directly
- Pydantic familiarity; a document store (anything with an upsert API)

## 1. The pipeline graph

```
START ──▶ parse_document ──▶ chunk_document ──▶ extract_fields ──▶ validate_extraction
                                                                          │
                                          ┌───────────────┬───────────────┤
                                     "RETRY"          "STORE"       "DEAD_LETTER"
                                          ▼               ▼               ▼
                                   extract_fields    store_records     quarantine
                                   (bounded loop)    (RetryConfig)
```

Five stages, one back-edge, three exits. The forward path is a plain sequence; validation is where the graph earns its keep, because a rejected extraction gets a bounded second attempt instead of poisoning the database.

## 2. Parse and chunk: deterministic stages with typed output

The first two nodes are pure code. Each declares what it hands downstream with a Pydantic model:

```python
from google.adk import Event, Workflow
from pydantic import BaseModel


class DocumentPayload(BaseModel):
    doc_id: str
    filename: str
    text: str


class ChunkPayload(BaseModel):
    doc_id: str
    chunks: list[str]


def parse_document(node_input: str) -> Event:
    """Raw upload (JSON envelope with base64 or plain text) → clean text."""
    import json
    payload = json.loads(node_input)
    return Event(output=DocumentPayload(
        doc_id=payload["doc_id"],
        filename=payload["filename"],
        text=payload["text"],
    ))


async def chunk_document(node_input: DocumentPayload) -> Event:
    """Split into overlapping chunks. Small state write for the retry loop later."""
    yield Event(message=f"Parsing complete: {len(node_input.text)} chars")
    chunks = split_with_overlap(node_input.text, size=1500, overlap=200)
    # `chunks` and the loop counter are read back by validate via its
    # `chunks` / `extract_attempts` parameters (state → parameter by name).
    yield Event(state={"chunks": chunks, "extract_attempts": 0})
    yield Event(output=ChunkPayload(doc_id=node_input.doc_id, chunks=chunks))
```

Two mechanics worth internalizing:

- **Structured data flows on the edge.** Any serializable value in `output` arrives at the successor as a typed object — no JSON parsing, no state reads. Attach `output_schema` on the producer or `input_schema` on the consumer to make the contract explicit and validated at runtime.
- **One `output` per execution, many progress events.** `chunk_document` yields three events but only one carries `output`, which is the rule: progress and state ride alongside, never instead of, the node's single output.

A candid note on `Event(state={"chunks": chunks})`: the docs are explicit that session state is a *lightweight* key/value store and should not carry large payloads — for real documents, keep chunks in an artifact or a database tool and pass a handle. We store them here so the validation loop can forward them without extra plumbing; swap in a `fetch_chunks(doc_id)` tool call in production.

## 3. Extract: the one LLM stage

Everything non-deterministic happens here, constrained by an output schema so downstream code never parses prose:

```python
from google.adk import Agent
from typing import Optional


class ExtractedFields(BaseModel):
    vendor: str
    invoice_number: str
    invoice_date: str
    total_amount: float
    currency: str
    line_items: list[dict]


class ExtractionResult(BaseModel):
    doc_id: str
    fields: ExtractedFields


extract_fields = Agent(
    name="extract_fields",
    model="gemini-flash-latest",
    mode="single_turn",
    output_schema=ExtractionResult,
    instruction="""
        You receive document chunks. Extract the invoice fields exactly as
        they appear. Use "" for genuinely absent string fields, 0.0 for
        missing amounts — never guess or invent values. Reply only with the
        JSON object matching the schema.
    """,
)
```

`output_schema` forces the model to answer in the `ExtractionResult` shape, so `validate_extraction` receives an object with fields — not a markdown blob. (In agent instructions you can also reference the structured input directly with the `{Class.field}` form; state-based `{key}` placeholders are a different mechanism and read session state, not node input.)

## 4. Validate: a function that routes

Validation is code. It computes problems and *routes* — returning `Event(route=...)` plus the data the next stage needs:

```python
from google.adk.workflow import DEFAULT_ROUTE


def missing_required(result: ExtractionResult) -> list[str]:
    problems = []
    if not result.fields.vendor:
        problems.append("vendor is empty")
    if not result.fields.invoice_number:
        problems.append("invoice_number is empty")
    if result.fields.total_amount <= 0:
        problems.append("total_amount must be positive")
    return problems


async def validate_extraction(
    node_input: ExtractionResult, chunks: list, extract_attempts: int = 0
) -> Event:
    """Route to STORE, RETRY (bounded), or DEAD_LETTER."""
    problems = missing_required(node_input)
    if not problems:
        return Event(route="STORE", output=node_input)
    if extract_attempts >= 3:
        return Event(route="DEAD_LETTER", output=node_input)
    yield Event(message=f"Extraction invalid ({problems[0]}) — attempt {extract_attempts + 1}")
    return Event(route="RETRY",
                 state={"extract_attempts": extract_attempts + 1},
                 output=ChunkPayload(doc_id=node_input.doc_id, chunks=chunks))
```

Three details make this loop honest:

- **The back-edge is legal because it is routed.** The engine rejects cycles made only of unconditional edges; a cycle must contain at least one routed edge — this is the graph equivalent of a `while` loop with a visible condition. `"RETRY": extract_fields` re-runs extraction with the *same* chunks, because `validate` forwards them as its `output`.
- **`chunks` and `extract_attempts` arrive from session state.** Function nodes receive state-backed values by parameter name — the same mechanism as the docs' `task_attempt_node(node_input, attempts: int)` example — which is why `chunk_document` wrote both keys earlier. State persists across the loop, so the counter climbs while the chunks stay available for re-forwarding.
- **`DEFAULT_ROUTE` and `DEAD_LETTER` are mandatory, not optional.** Unexpected route values and permanently broken extractions land in `quarantine`, a real handler, instead of vanishing:

```python
def quarantine(node_input: ExtractionResult) -> Event:
    DEAD_LETTER_TABLE.upsert(node_input.model_dump())
    return Event(message=f"Quarantined {node_input.doc_id} for manual review")
```

## 5. Store: the tool node with a retry policy

Storage is the stage that must survive transient database failures. ADK lets you attach a retry policy and a per-attempt timeout directly to a node:

```python
from google.adk import Context
from google.adk.workflow import RetryConfig, NodeTimeoutError, node


class DatabaseBusyError(Exception):
    """Transient failure from the document store."""


@node(
    retry_config=RetryConfig(
        max_attempts=3,            # 1 original attempt + 2 retries
        initial_delay=1.0,         # seconds before the first retry
        exceptions=[DatabaseBusyError, NodeTimeoutError],
    ),
    timeout=10.0,                 # seconds allowed per attempt
)
async def store_records(ctx: Context, node_input: ExtractionResult) -> Event:
    yield Event(message=f"Storing {node_input.doc_id} (attempt {ctx.attempt_count})")
    try:
        upsert(node_input)        # idempotent on (doc_id, invoice_number)
    except DatabaseBusyError:
        raise                     # retry policy decides what happens next
    yield Event(output={"doc_id": node_input.doc_id, "status": "stored"})
```

The policy mechanics from the [retries docs](https://adk.dev/graphs/retry/):

- **`max_attempts` counts the original attempt** — 3 means 2 retries. `0` or `1` disables retries.
- **Backoff compounds**: defaults of 1s initial delay and a 2.0 factor give waits of 1, 2, 4, 8 seconds, plus jitter so simultaneously failing nodes do not stampede.
- **Retry only transient errors.** By default a policy retries almost everything; bad input and bugs fail identically on every attempt, so listing `exceptions` (connection errors, timeouts, rate limits) fails fast on the rest.
- **`ctx.attempt_count` starts at 1**, so your code can log which attempt is running.
- **Make retried work safe to repeat.** A retry re-runs the whole node — if it wrote before failing, the write happens twice. Upsert on a natural key, or move the side effect into a separate node that runs after the unreliable call succeeds.

Nodes without a retry policy are not retried at all: when attempts are exhausted, the last error fails the workflow.

## 6. Two layers of retry for flaky extraction

"Flaky extraction" is really two problems, and the graph gives you a distinct mechanism for each:

| Failure | Layer | Mechanism |
|---|---|---|
| Transient (API 429/503, DB busy, timeout) | Node level | `RetryConfig` + `timeout` on the node that calls the service |
| Semantic (schema-valid but wrong/missing fields) | Graph level | Routed `RETRY` back-edge, bounded by `extract_attempts` in state |

Layer one retries *infrastructure*; layer two retries *reasoning* — and crucially, layer two is bounded at three attempts before `DEAD_LETTER`. An unbounded "make the model try again" loop is how pipelines quietly burn a thousand dollars on one corrupt PDF.

One documented limitation to respect: **the attempt count for a node's retry policy is kept in memory for the current run.** If the workflow pauses (human input) or the application restarts, a node that runs again starts from attempt 1 with all attempts available. The validation loop's `extract_attempts` counter lives in session state instead, so it survives — keep the two counters conceptually separate.

## 7. Assembling the workflow

```python
root_agent = Workflow(
    name="document_pipeline",
    edges=[
        ("START", parse_document, chunk_document,
                  extract_fields, validate_extraction),
        (validate_extraction, {
            "STORE": store_records,          # happy path
            "RETRY": extract_fields,         # bounded back-edge
            "DEAD_LETTER": quarantine,       # gave up
            DEFAULT_ROUTE: quarantine,       # router botched a value
        }),
    ],
)
```

The dispatch table is data — printable, reviewable in a diff — while the decision rule lives in `validate_extraction` as a unit-testable function. Run it by iterating `runner.run_async(...)` and you will see progress messages, the routed decision, and the final store confirmation as separate events.

## 8. Scaling notes

- **Fan out per document with a `JoinNode`.** Multiple documents run in parallel as separate `START` rows that converge on a join, which waits for every predecessor and passes a record keyed by predecessor node name to a merge node:

  ```python
  edges=[
      ("START", process_doc_a, merge),
      ("START", process_doc_b, merge),
      ("START", process_doc_c, merge),
      (merge, summarize_batch),
  ]
  ```

  Every node feeding a join **must produce an output** — a predecessor finishing without one leaves the join with a hole, and the failure surfaces downstream, far from the cause. Attach a retry policy to any join-fed node that can fail.

- **Do not move bulk data through state.** Session state is a lightweight store; large text belongs in artifacts or your document database. Pass handles on the edge, payloads in storage — and keep side effects idempotent, since retries and at-least-once semantics exist somewhere in the stack.
- **One workflow, one runtime process.** The graph engine runs nodes inside a single runner and session; parallel paths are concurrent tasks in that process, not distributed workers. If a stage outgrows that — video OCR, hour-long parsing — split it into a queue-backed service and call it from a tool node, or read up on [distributed graph execution](/posts/adk-distributed-graph-execution-workers/) for what ADK does and does not give you out of the box.

## 9. Checklist

- [ ] Every stage boundary has a Pydantic model; no stage consumes raw prose.
- [ ] Exactly one `output` per node; progress uses `Event(message=...)`.
- [ ] The LLM stage has `output_schema`, so validation gets typed fields.
- [ ] Validation routes — `STORE` / `RETRY` / `DEAD_LETTER` — plus `DEFAULT_ROUTE`.
- [ ] The retry back-edge is bounded by a state-backed attempt counter.
- [ ] Transient-failure nodes carry `RetryConfig` with an `exceptions` filter and a `timeout`.
- [ ] Storage is idempotent under repeat runs, and bulk data lives in artifacts/DB rather than session state.

## Conclusion

The model in this pipeline does exactly one job — turning chunks into structured fields — and everything around it is deterministic code with typed contracts, a bounded repair loop, and a retry policy tuned to transient failures. That is the point of graph workflows: you are not asking a prompt to remember your error handling. The topology *is* your error handling, and it is reviewable before the first document ever arrives.

## References

- https://adk.dev/workflows/
- https://adk.dev/graphs/
- https://adk.dev/graphs/routes/
- https://adk.dev/graphs/data-handling/
- https://adk.dev/graphs/retry/
- https://github.com/google/adk-python
