@asConnection turns a list field into a Relay connection: the schema-transform stage rewrites [T!]! to a synthesised TConnection, the generator emits keyset SQL, and the runtime returns edges, nodes, pageInfo, and (when asked for) totalCount. The reference page covers signature, examples, and constraints. This recipe addresses three operational questions that bite teams in review: why each connection field should own its own Connection type, what totalCount actually costs (and how it batches under nested connections), and how the default and the maximum page size are decided.
For the cursor-stability and tie-breaker side of pagination, see How-to: Sort results. The sort spec and the connection are separate concerns: the order is what the cursor encodes, and the connection is what the cursor traverses.
Synthesised vs declared connection types
Two paths produce a connection type, and the rewrite recognises both:
-
Directive-driven (synthesised).
myField: [T!]! @asConnectionon a bare list. The generator manufactures<ParentType><FieldName>Connectionand a matching Edge type named<ParentType><FieldName>ConnectionEdge, registers them on the schema, and rewrites the field’s return type to point at the synthesised name.Query.stores: [Store!]! @asConnectionbecomesQuery.stores: QueryStoresConnection!, alongside aQueryStoresConnectionEdge. -
Structural (declared).
myField: FilmsConnection!where the SDL already declaresFilmsConnection { edges: [FilmsEdge!]!, nodes: [Film!]!, pageInfo: PageInfo!, totalCount: Int }. The rewrite recognises theedges.nodeshape and reuses the SDL type as-is.@asConnectionmay also be present on the carrier, but the directive’s job is just to opt the field into the connection emitter; no rewrite of the return type happens.
The Sakila example schema uses both shapes intentionally: Query.stores exercises the synthesised path (QueryStoresConnection), and Query.filmsConnection: FilmsConnection! exercises the declared path. Both compile to the same kind of fetcher; the difference is purely which side owns the type’s name.
One field, one connection type
Each @asConnection field gets its own synthesised Connection type, named <ParentType><FieldName>Connection. The default is the recommended outcome: a field-specific type for a field-specific result set. The connectionName: argument that overrides the default is deprecated; reach for it only when migrating a legacy schema.
The reason is semantic, not syntactic. Two fields that paginate the same element type usually do not return the same logical result:
-
Different parents.
Query.customersreturns the global customer list;Store.customersreturns one store’s customers. The element type isCustomerin both cases, but the result sets are scoped differently. A sharedCustomersConnectionwould lie about that scoping at the type level: a tool inspecting the schema would see one connection and assume one filter contract, when the runtime contracts differ. -
Different filters and arguments. A connection field’s argument set is part of its identity.
Query.activeCustomers(active: Boolean = true)andQuery.customersproduce different sub-populations of the same table; a shared Connection type would erase that distinction. -
Different orders, different cursors. The cursor wire format embeds the active sort columns. Two fields that have different
@defaultOrder(or different@orderByenum spaces) cannot share cursors, even when they share an element type. Sharing the Connection type but not the cursor format produces a leaky abstraction at the schema boundary. -
Independent evolution. Two fields that share a type evolve in lockstep: adding a column to one’s order spec, adding a filter to one’s element shape, or renaming one’s edge metadata forces the other to follow. Field-owned Connections decouple that lifecycle.
The synthesised default <ParentType><FieldName>Connection honours all four points by construction. Query.customers becomes QueryCustomersConnection and Store.customers becomes StoreCustomersConnection; they’re separate types in the schema because they’re separate things in the domain. Clients that need to pass both lists through the same UI component still can — the GraphQL types are independent, but the underlying Customer element shape is shared.
The deprecated connectionName: override coalesces multiple carriers onto one type. It exists for one purpose: migrating a legacy schema where the wire-side name is already published and a rename would break clients. New schemas should not use it; legacy schemas should plan a transition off it. The dedup is also silent — two carriers with the same name but different element types reuse the first registration without validation, producing a connection whose edges.node doesn’t match one of the carriers — which is a sharp edge worth avoiding for that reason alone.
totalCount is lazy and orthogonal
totalCount: Int is optional on every connection (synthesised or declared). The reference page documents the field; the operational facts are:
-
Lazy on selection. graphql-java only invokes the registered
totalCountresolver when the client selects the field. Queries that ask foredges,nodes, orpageInfoand skiptotalCountpay zero count cost. This is whytotalCountisInt(nullable), notInt!: the resolver can decline to produce a value, and the field’s nullability lets the caller observe that. -
Issued as a separate
SELECT count().* The page query and the count query are independent SQL passes. The count uses the sameTable<?>andConditionthe page used (the root connection fetcher builds its connection with a count over them), so the count matches the page’s predicate; it does not duplicate the page’s projection orseek/limit. -
One grouped count per batch on nested connections. A connection nested under a list of parents, such as
Film.actorsConnectionunderfilmById, or a connection over a union nested under a list, is fetched for all parents in one batched page statement. SelectingtotalCountthere adds one more statement for the batch,count(*)grouped by parent, however many parents the batch holds; each parent reports its own count, independent offirstand the cursor. -
Each field counts its own result set. The type gives the shape; what fills
totalCount, andfacetswhere the connection has them, is the field’s own count and facet queries, over its own arguments. Two fields sharing one connection type throughconnectionName:share the class, not the numbers: each counts, and buckets its facets, under the filter its own arguments build. They must still surface the same facets, which@asFacetconstraints states.
The performance consequence: keep totalCount available in the schema for clients that need it, but do not assume it costs nothing per query. A client that always asks for totalCount doubles the round trip count; for high-RPS reads, prefer not selecting it.
Page size: the default and the maximum
Page size resolves at request time:
-
Client supplies
first: Norlast: N. UseN. -
Client supplies neither. Use the directive’s
defaultFirstValue:, or 100 whendefaultFirstValue:is also omitted. The default appears in your published schema as thefirstargument’s default value.
Then, if the build sets <maxAllowedPageSize>, a page size above it is lowered to it. The client is not told with an error; it sees a full page and hasNextPage: true (or hasPreviousPage: true for last:), and follows the cursor as usual. With <maxAllowedPageSize>1000</maxAllowedPageSize>, first: 5000 returns 1000 rows. Without the parameter there is no maximum, and a client passing first: 100000 gets that many rows.
defaultFirstValue: is a default, not a maximum. With <maxAllowedPageSize> set, the built-in default of 100 becomes the maximum when the maximum is smaller (<maxAllowedPageSize>50</maxAllowedPageSize> publishes first: Int = 50), and a defaultFirstValue: you wrote that is larger than the maximum fails the build, since no request could receive it.
The maximum covers connections only. A plain list field with a first: argument is not a connection and is not limited by it.
Cursor encoding is part of the public contract
A cursor names one row’s position in the active order: the values of the order’s columns for that row, written as a JSON array with one element per column in order and no whitespace, then encoded as URL-safe Base64 without padding. Each element is the column’s database value, so a column with a jOOQ converter contributes its database type’s value, not the converted one. The column’s SQL type decides how it is written:
-
SQL
NULL:null. -
A numeric column: a bare JSON number without trailing fractional zeros,
2.5rather than2.50. A floating-point NaN or infinity, which JSON cannot hold, is written as a string. -
A boolean column:
trueorfalse. -
A date column: a date-time,
"2017-08-15T00:00:00", with the time of day when the column’s Java type carries one. -
A timestamp column:
"2017-08-15T13:45:10". A non-zero fraction of a second is written to six digits, or nine when the value needs them,"2017-08-15T13:45:10.120000". With a time zone, the fraction is always written and the offset follows it,Zfor UTC:"2017-08-15T13:45:10.000000+01:00". -
A character, uuid or enum column: a JSON string of its value, an enum as its database literal.
-
Any other column: a JSON string holding the database’s own text for the value, what
cast(column as varchar)returns. The database reads it back when the next page is fetched, so the cursor names exactly the value the row holds: a range ending ininfinitystays distinct from one with no upper bound, and an array, abyteaor a network address pages like any other column.
Graphitron checks a cursor when it decodes it, and answers a malformed one with cursor is not valid. The exception is the text of a column in the last group, which only the database can read: a cursor edited so that this text is no value of the column’s type fails when the page is fetched, as an unmatched exception with a correlation id.
Clients should still treat a cursor as opaque. The format is stated here because it is a compatibility promise, not an interface to build on.
Graphitron 9 issued the same bytes on Oracle, so a cursor pinned in a Graphitron 9 test keeps its value, and a cursor a client stored under Graphitron 9 keeps working while the connection pages on the same columns. Some Graphitron 9 cursors still read back but are not the bytes Graphitron 10 writes for the same row: those issued on PostgreSQL, which wrote a space after each comma, kept a number’s trailing zeros and wrote a date without a time; and those of a nested connection holding a decimal number. A cursor for a row with a NULL order column does not read back: Graphitron 9 on Oracle left the element out, a cursor Graphitron 9 could not page from either, and Graphitron 10 rejects it and writes null in its place. Two kinds of connection are an exception as well, and a client drops a cursor it stored from one and restarts from the first page:
-
A connection whose order does not identify a row. Graphitron now appends the table’s primary key to it (see How-to: Sort results), so a Graphitron 9 cursor has too few values and is rejected.
-
A connection over a multi-table interface or union. Graphitron 9 wrapped its cursors in an object naming the type, which Graphitron 10 rejects.
A cursor a Graphitron 10 release candidate issued is still read, so a client that stored one keeps its place after the upgrade while the connection pages on the same columns. The release candidates wrote their own format; graphitron reads it and writes only the format above, so the next cursor the client receives is in the new form. A release-candidate cursor its own release could not page from either is still rejected: one on an enum order column whose value differs from the enum constant’s name, such as NC-17, and one on an order column with a converter whose value does not read back from its text.
Three consequences worth restating here (the sort recipe covers the full set):
-
The cursor’s columns are the order’s columns. Adding, removing, or reordering columns in
@defaultOrderor in an@orderenum value invalidates outstanding cursors. So does changing the table’s primary key, which graphitron appends to an order that does not already identify a row. Treat the order column list as part of the cursor wire contract. -
Decoding rejects shape mismatches. When the request’s effective order produces a different column count than the cursor decodes, the request fails. A cursor issued under
@orderBycannot be replayed against a@defaultOrder-only request unless the column lists happen to coincide. -
An empty cursor is no cursor.
after: ""andbefore: ""(or a whitespace-only value) read as if the argument were omitted, so an operation that declares$after: String!can fetch the first page by sending the empty string.
Backward pagination reuses the same encoding; the rewrite reverses each SortField’s direction via jOOQ’s `$field()/$sortOrder() model API, runs the seek, and reverses the in-memory result before returning. A cursor issued from a first: page round-trips through a before: request and vice versa.
Child connections
A connection under a non-root type, made one by @asConnection or by returning a hand-written connection type, is always fetched in a query of its own, batched across parents through a DataLoader. The batch query carries a ROW_NUMBER() OVER (PARTITION BY parentInput.idx ORDER BY …) envelope so each parent’s connection page is the leading N+1 rows of its partition: each parent pages its own rows. @splitQuery is inferred there, so it is not written; writing it draws the SPLIT_QUERY_REDUNDANT warning.
type Film @table(name: "film") {
actorsConnection(
first: Int, last: Int, after: String, before: String
): ActorsConnection! @reference(path: [
{key: "film_actor_film_id_fkey"},
{key: "film_actor_actor_id_fkey"}
]) @defaultOrder(primaryKey: true)
}
The totalCount consequence cited above applies here: a split connection counts every parent of the batch with one grouped statement.
Constraints and pitfalls
-
@asConnectionapplies to list-typed fields. Single-cardinality@asConnectionis rejected at classify time. -
The field must have a stable order: the primary key of the table its target type is bound to, an
@defaultOrder, or a non-null, single-valued@orderByargument. A nullable@orderByargument does not count, since a client may leave it out; without one of these, keyset pagination has no anchor and the build fails withLIST_ORDER_UNDETERMINED. -
connectionName:is deprecated. Each connection field should own its own Connection type; the override exists as a transition mechanism for legacy schemas. When set, the dedup is silent — two carriers with the same name and different element types reuse the first registration and only the first carrier’s element type appears under that connection’sedges.node. -
totalCounton a nested connection costs one grouped statement per batch of parents, not one per parent. -
totalCountis lazy on selection but a separate SQL pass when selected. Treat it as observable extra cost; don’t assume it’s free. -
defaultFirstValue:is the omitted-first:default, not a maximum. Set<maxAllowedPageSize>to cap every connection’s page size; without it a client gets as many rows as it asks for. -
Cursor wire format embeds the active order’s columns. Sort-spec changes invalidate outstanding cursors; treat the column list as part of the public contract.
-
A child connection is always paged per parent, with or without
@splitQuery; the directive is inferred there and, written, draws a redundancy warning.
See also
-
@asConnectionestablishes the connection wrapper. -
@splitQueryis the batched fetch a child connection always takes, inferred rather than written. -
@defaultOrderanchors the cursor. -
@orderBysupplies dynamic order. -
How-to: Sort results covers cursor stability, tie-breakers, and the collation pitfalls that bite at scale.
-
How-to: Polymorphic types covers union/interface connection emission and how a multi-table connection orders and seeks on its participants' primary-key columns.