CouchGraph: just relax

The documents in CouchDB, handed to the AI as a graph: one question, one query, and nobody has to understand the database.

Time to relax

When CouchDB starts, it writes to the log: "Apache CouchDB has started. Time to relax." It is not a throwaway joke: relax is the project's motto, right under the logo. The idea is that the database is easy to use, takes a beating in production without drama, and a problem in one request stays in that request.

In an operation run by agents, that fits nicely. A collector pulls data from an external API all day and keeps it all in Couch. Every morning the agent has to read that data and answer questions: what came in yesterday, what is stuck, who is the customer behind that order. This post is about how we made that reading easy for the AI: CouchGraph, which hands Couch's documents over as a graph.

External APIwhere the data livesCollectorGET only, incrementalCouchDBone JSON per objectCouchGraphGraphQL, read onlyAgentone question, one graph
Nobody writes to the source, and nobody writes to Couch but the collector. The agent only reads, through the graph.

Why CouchDB for this

Under it all, Erlang

CouchDB is written in Erlang, on top of OTP, the same platform that was born for telephone switches: systems that cannot stop, with a lot happening at once. A good part of the motto's relax comes from here.

Just relax: the collector went down at night? It comes back and carries on where it stopped, because what is open lives in a view, not in memory. A document was written twice? It became a revision, and the hash prevents the second one. The agent asked a crooked question? The endpoint is read only. You can sleep.

HTTP first, replication and clustering

The other half of the relax: Couch was made to live on a network. It is not a database with an HTTP API bolted on; HTTP is its protocol, even between its own nodes.

master-masterCouch Atakes writesCouch Btakes writes_changes_changesconflict? one revision wins the same way on both sides,the others stay in _conflictsclusterhttps://couch:5984node 1s1s2node 2s1s2node 3s1s2
In both drawings the client only sees HTTP. What changes is how many copies exist and where.

For CouchGraph this comes for free. It only talks HTTP, so it does not matter whether the other side is one node, a cluster or a replica made just for the agents to read without touching the database the collector writes.

The problem: loose documents

A document is great for keeping what the source returned, and poor at answering relationship questions. An order knows its customer's _id in a customer_ref field; that order's payments are in a view. To answer "what happened to order 7", the agent has to know every view's name, build keys, fetch document by document and join it all in its head. It works. It burns context, gets joins wrong and makes up fields.

The links were already there: the *_ref fields and the views. Something just had to say it out loud, in a format the agent reads in one go. A graph.

Next: the graph, at a glance →

The same documents, as a graph

CouchGraph is a GraphQL server that sits in front of a CouchDB database. Every document type becomes a schema type; every *_ref becomes an edge from child to parent (belongsTo); every one-to-many view becomes the way back, from parent to children (hasMany). The agent stops thinking in documents: it thinks of the order and walks the links.

Pick a question and see which part of the graph it walks.

customer_refcustomer_reforder_reforder_reforder_refaddress_refcustomer:c_1activeorder:o_7completedorder:o_9processingpayment:p_3completedshipment:s_2deliveredaddress:a_5payment:p_4processing
Every edge is a *_ref field (belongsTo). Read the other way, from parent to children, it is a view (hasMany).

Every node is a Couch document, with the _id the collector gave it. Nothing was copied: the graph is just a way to read.

{
  order(id: "order:o_7") {
    status
    customer { data address { data } }
    payments { status data }
    shipments { status }
  }
}

What changes for the agent

Loose documentsGraph
Find out what existsread loose documents and guess the fieldsread the schema: types, fields and links, with descriptions
Follow a linktake the customer_ref and ask for another documentask for the customer field
List the childrenknow the view's name and build the keyask for the orders field
Round tripsone per documentone per question
Writing by accidentthe same HTTP that reads also writesthere is no mutation

The biggest win is not even the query. It is the schema. An agent that has never seen the database asks for the introspection, reads the types, the links and the descriptions, and already knows what it can ask. The documentation lives where the data lives, and it cannot go stale without breaking the build.

Where the idea came from

It came from seeing Sibelius's graphql-relay-visualize: an app that draws, with live diagrams, what GraphQL and Relay do under the hood, including the normalized store as a graph of records linked by id. Looking at it, it was obvious that Couch's documents were already a normalized store waiting for someone to draw the edges.

Next: the files and the procedure →

One document, as the collector stores it

The top-level fields belong to the collector, for linking and filtering. The source object goes whole into data.

{
  "_id": "order:o_7",
  "type": "order",
  "source_id": "o_7",
  "status": "completed",
  "open": false,
  "hash": "sha256:…",
  "collected_at": "2026-12-01T10:12:00Z",
  "customer_ref": "customer:c_1",
  "data": { "…": "the raw object the source returned" }
}

The view that becomes a hasMany

// _design/store, view orders_by_customer
function (doc) {
  if (doc.type === "order" && doc.customer_ref) {
    emit(doc.customer_ref, null);
  }
}

CouchGraph's files

A workspace with one project per database. Each project gets its own route (/store/query), and the workspace locks them all.

couchgraph/
  couchgraph.yaml          # workspace: connection, port, auth; one project per database
  store/
    couchgraph.yaml        # the database, indexes, design docs
    schema/store.graphqls  # types, links and queries
couchdb:
  url: ${COUCHDB_URL}
  user: ${COUCHDB_USER}
  password: ${COUCHDB_PASSWORD}

projects:
  - ./store            # served at /store/query

server:
  port: 8080
  playground: false
  readOnly: true       # every mutation is rejected

auth:
  enabled: true
  requireAuth: true    # even reads need a token (JWT)
  jwtSecret: ${JWT_SECRET}
couchdb:
  database: store

schema:
  core: true           # document, findDocs, queryView next to the typed schema
  paths:
    - schema/**/*.graphqls

designDocs:
  sync: manual         # the views belong to the collector, not to CouchGraph

indexes:
  - name: idx_type_status
    fields: [type, status]

The schema

@collection says which document type that type is. @belongsTo reads a *_ref. @hasMany calls a view. @get and @find become the entry points. The quoted descriptions are what the agent reads.

"""
Order collected from the source. data is the raw object.
"""
type Order @collection(type: "order") {
  id: ID!
  status: String
  "true while the order has not reached a final status."
  open: Boolean!
  data: Map
  customer: Customer @belongsTo(field: "customer_ref")
  payments: [Payment!]! @hasMany(view: "store/payments_by_order")
  shipments: [Shipment!]! @hasMany(view: "store/shipments_by_order")
}

type Customer @collection(type: "customer") {
  id: ID!
  data: Map
  address: Address @belongsTo(field: "address_ref")
  orders: [Order!]! @hasMany(view: "store/orders_by_customer")
}

extend type Query {
  order(id: ID!): Order @get
  orders(status: String, limit: Int = 50, bookmark: String): [Order!]!
    @find(selector: "{\"status\": \"$status\"}")
}

The question, from outside

It is just a POST. The token lives in an environment variable; never in the prompt, never in a file.

curl -s https://graph.example.com/store/query \
  -H "Authorization: Bearer $READ_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"query":"{ orders(status: \"processing\") { id customer { data } } }"}'

The rules that hold the graph

The procedure

  1. Collect. A process that only sends GET to the source and stores one document per object, with a hash so nothing changes when nothing changed.
  2. Link. When storing, the collector fills the *_ref fields with the related document's _id (and stores that document too, if it does not exist yet).
  3. Index. One view per one-to-many link (orders_by_customer...) and one Mango index per filter the agent will use.
  4. Describe. A .graphqls with @collection, @belongsTo, @hasMany and the queries. The schema's descriptions are the manual the agent reads.
  5. Lock and serve. readOnly, requireAuth, a read token for the agent. Playground only when needed, and still with a token.
  6. Teach the question. In the agent's skill, the URL, the token's variable name and two or three ready queries. It finds the rest in the schema.

How to know it worked

In the end: Couch keeps, the collector feeds, CouchGraph draws the edges, and the agent reads. Nobody has to understand the database to ask a good question. Time to relax.

References

greetz sibelius for graphql-relay-visualize, which sparked this idea