Relay Global Object Identification gives every node a single opaque ID that identifies a row across the graph. Graphitron synthesises that ID from (typeId, primary-key columns) whenever a type carries @node and an id: ID! field decorated with @nodeId. Query.node(id:) and Query.nodes(ids:) dispatch on the embedded typeId to fetch the underlying row. This recipe covers the choices that affect long-term ID stability, the contract for decoding IDs back into typed keys at argument and input sites, and the dispatch shape of the two root entry points.
Wire format and the opacity contract
The opaque ID is base64-url-encoded "typeId:v1,v2,…" (no padding, UTF-8). Commas inside values are escaped as %2C. Generated NodeIdEncoder.encode<TypeName>(…) and NodeIdEncoder.decode<TypeName>(base64Id) helpers handle the round-trip.
Two things follow from the wire format:
-
The
typeId, thekeyColumns, and the order of those columns are part of the public ID contract. Changing any of them invalidates IDs that clients have already cached or persisted. -
A malformed ID is a client error on every path but federation’s
_entities, which keeps anullslot for it.Query.node(id:)andQuery.nodes(ids:)fail with the same message an argument gives for an ID that cannot be read as a node ID at all, or whose key does not decode for a type this subgraph serves; innodesthe error sits at that ID’s own position. They returnnullfor a well-formed ID of a type this subgraph does not serve, and for one naming no row (Relay spec). On the argument path, decode errors surface asGraphqlErrorExceptionbecause the request is asserting "these are valid IDs of this type"; see "Decode-side errors" below.
Stable-ID strategies
@node(typeId:) defaults to the GraphQL type name. Two reasons to set it explicitly.
Decouple from rename. If Customer might one day be renamed to Person, set typeId: "C" (or "customer", or any opaque token) at introduction time so the rename is a schema-only change:
type Person implements Node @table(name: "customer") @node(typeId: "C") {
id: ID! @nodeId
}
Already-issued IDs continue to decode after the rename because the wire format never carried the GraphQL name.
Shorter or namespaced IDs. The typeId is part of every ID’s wire bytes. Trimming Customer (8 bytes) to C (1 byte) compounds across batched lookups. Conversely, prefixing typeId per service (shop:Customer) is one way to keep IDs unique across federated subgraphs without coordinating on type names.
A federated graph can also publish each node type’s typeId in the supergraph, which lets a dedicated node subgraph decode an ID without calling the owning subgraph; see Publish typeIds to the supergraph.
The build rejects two @node types that share a typeId (whether explicit or defaulted): Query.node(id:) cannot dispatch unambiguously, and the rewrite refuses to compile rather than silently route to the wrong table.
keyColumns migrations
The default @node(keyColumns:) is the bound table’s primary-key columns in declaration order. Override only when the PK is unstable (rare on production schemas) or when an alternate unique key is the better identity:
type FilmByCode implements Node @table(name: "film") @node(keyColumns: ["FILM_CODE"]) {
id: ID! @nodeId
filmCode: String! @field(name: "FILM_CODE")
}
FILM_CODE must be a unique key on film for the build to accept the directive; the build fails to resolve otherwise.
When you genuinely need to migrate keyColumns (the underlying PK is being changed, or you’re moving from PK-based IDs to a domain-key for stability), the safe sequence is:
-
Add the new candidate-key columns and a unique constraint, deploy, backfill.
-
In a single release swap
keyColumns:to the new column list. Every client cache or persisted ID issued before this release stops decoding; plan accordingly. -
Optionally retain the old type under a different
typeId(and a deprecation marker) for one release cycle so old IDs continue to dispatch while clients refresh.
Narrowing the key, dropping columns from keyColumns and keeping the rest, has a rolling window: move the old list to legacyKeyColumns and ids issued in the old shape keep resolving while every new id uses the narrowed one; see Narrowing the key. Widening the key, reordering it, or swapping in an unrelated key is still a hard cut: every id issued before the change stops decoding. If continuity matters there, the right tool is a second @node type pinned to the old shape, not a graceful in-place migration.
Composite-PK nodes
Composite primary keys work the same way; the synthesised ID embeds every column in declaration order:
type FilmActor implements Node @table(name: "film_actor") @node {
id: ID! @nodeId
# ...
}
film_actor’s PK is `(actor_id, film_id); the wire format is base64-url("FilmActor:<actor_id>,<film_id>"). @lookupKey on [ID!]! keyed by FilmActor produces a VALUES(idx, actor_id, film_id) join over both PK columns; no per-element scatter is needed.
Reordering the PK columns at the catalog level changes the ID’s wire format. If your jOOQ catalog regenerates the columns in a different order (e.g. after a DDL rewrite), set keyColumns: explicitly to lock the order:
type FilmActor implements Node @table(name: "film_actor")
@node(keyColumns: ["actor_id", "film_id"]) {
id: ID! @nodeId
}
Cross-type IDs from FK paths
@nodeId without typeName: infers from the containing type when the field is on a @node type’s own id slot. When the slot encodes a different row’s identity, set typeName: explicitly and pair it with @reference:
type Customer implements Node @table(name: "customer") @node {
id: ID! @nodeId
addressNodeId: ID @nodeId(typeName: "Address")
@reference(path: [{key: "customer_address_id_fkey"}])
}
addressNodeId produces an Address global ID from the FK column on customer. Two things happen at projection time. First, the FK-mirror collapse: because customer.address_id == address.address_id, the rewrite reads the PK columns directly from the customer row without joining to address. Second, the encoder uses Address’s typeId and `keyColumns, not Customer’s. The result is a valid `Address ID that Query.node will dispatch to the address table.
The same pattern works for any FK that lands on a @node table. If two @node types bind to the same target table (rare but legal), set typeName: explicitly to disambiguate; inference rule (b) only fires when exactly one @node type matches.
Decode-side: arguments and inputs
@nodeId on an argument or input field reverses the direction: it decodes an opaque ID back into typed key columns. Two shapes are common.
Same-table NodeId argument. The argument decodes to the surrounding query’s PK columns and feeds an IN (…) lookup. @lookupKey is implicit on this shape:
type Query {
filmsByNodeIdArg(ids: [ID!]! @nodeId(typeName: "Film")): [Film!]!
}
The rewrite emits a VALUES(idx, film_id) JOIN film ON film.film_id = values.film_id shape, with each id decoded via NodeIdEncoder.decodeFilm(…) at request time. Adding an explicit @lookupKey is permitted but redundant.
Composite-PK NodeId argument. When the keyed type has a composite PK, the same shape widens to a multi-column VALUES:
type Query {
filmActorByNodeId(id: [ID!]! @lookupKey): [FilmActor!]!
}
Here @lookupKey is explicit because the keyed type is inferred from the return type, not from @nodeId(typeName:). The decoder yields (actor_id, film_id) per ID; the join is VALUES(idx, actor_id, film_id) JOIN film_actor ON … AND ….
Input-record field. The same decode contract applies inside an input type used in a mutation or filter:
input FilmSameTableNodeIdInput {
filmIds: [ID!] @nodeId(typeName: "Film")
}
The rewrite materialises filmIds as List<Integer> (or the typed PK shape) on the input record, with decode happening at the boundary.
Decode-side errors
Argument and input decoders use the ThrowOnMismatch contract: a malformed base64 ID, or an ID whose embedded typeId does not match the declared typeName:, fails the request as a GraphitronClientException before any SQL runs. Clients see a structured GraphQL error whose path names the field that received the argument; the server never tries to use a half-decoded value as a query parameter.
The message echoes the ID and names the type the argument expects, telling a malformed ID from a well-formed ID of another type:
Invalid node id "bm90LWFuLWlk" for this argument: not a valid Film id
Invalid node id "Q3VzdG9tZXI6MQ" for this argument: decodes to type "Customer", expected a Film id
Every @nodeId site fails with this text: a filter, a lookup argument, a @service argument and a @mutation input field alike, whether the ID is a node’s own identity or a reference to another node. Because it is a client error, a mutation without an errors channel reports it to the client rather than redacting it to a log reference, and a payload whose @error handler names GraphqlErrorException claims it as it claims any other client error.
Query.node(id:) and Query.nodes(ids:) refuse a malformed ID the same way, with not a valid node id for one that cannot be read as a node ID at all and not a valid <Type> id for one of a type this subgraph serves whose key does not decode. The asymmetry left is about type: an argument asserts one type, so a well-formed ID of another type is an error there, while Query.node(id:) queries whether an ID resolves at all and answers null for an ID of a type this subgraph does not serve (another subgraph may own it) and for one naming no row (per Relay’s "if no such object exists, the field returns null").
Invalid node id "ikke-en-id" for this argument: not a valid node id
An ID also has to carry key values its columns can hold. It decodes only if every key value is exactly one graphitron could have written for a value of its column. Non-numeric text, a number outside the column’s range or precision, and a padded or reformatted number (" 1", "01", "1.0" for an integer key) all make the ID malformed, with the outcome above: the client error on node and nodes, at the ID’s own position in nodes with the rest of the batch resolving, null on _entities with the rest of its batch resolving, and a client error on an argument or input. Such a value is never bound into SQL, so a forged ID cannot wrap onto another row: Customer:4294967297 over an int4 key is malformed, not customer 1. On a column with a jOOQ converter, the check follows the value through the converter to its database value and back.
A @nodeId argument on a field returning an interface or union
What the argument asserts is a set of types when the field returns a multi-table interface or union and the @nodeId carries no typeName:. Each implementation infers its own node type from its own table, so one argument means "a Customer ID" against the customer table and "a Staff ID" against the staff table:
union AddressOccupant = Customer | Staff
type Query {
occupantById(id: ID! @nodeId): AddressOccupant
}
The generated fetcher dispatches: each branch of the query matches only the IDs it can decode, so exactly the branch owning the supplied ID returns a row, and a Relay client gets what the schema shape promises. The assertion still holds, over the candidate set rather than over a single type: an ID that no implementation can decode fails the request as a GraphitronClientException naming every candidate, before any SQL runs.
Invalid node id "MjAwMTE6LTE2" for this argument: decodes to type "20011", expected an id of one of: Customer, Staff
Two shapes stay outside dispatch. Writing @nodeId(typeName: "Address") pins one node type for every branch, which is the shape to reach for when the argument really does mean one type (an FK-target filter, say), and it keeps the single-type error message. And a bare @nodeId on a nested input field of such a field is rejected at build time rather than dispatched: name the type explicitly there.
Multitable filter inputs
A @nodeId filter on a query returning a multi-table interface decodes once and filters each participant branch. When every participant reaches the target through a unique single-hop FK, discovery is automatic. When a participant’s route is ambiguous or longer, state it per participant with @referenceFor:
input ApplicationFilter {
environmentId: ID @nodeId(typeName: "Environment")
@referenceFor(type: "FeideApplication", path: [{key: "feide_app_environment_fkey"}])
@referenceFor(type: "IdmApplication", path: [{key: "idm_app_env_fkey"}])
}
type Query {
applications(filter: ApplicationFilter): [Application!]!
}
The path runs from each participant’s own table toward the target, which is the direction the generated predicate reaches in. Participants you do not name keep automatic discovery.
When no generated route fits, @condition(override: true) on the leaf hands the whole predicate to your method: it receives each branch’s table and, projected with argMapping:, the leaf’s decoded key column (an Integer for Environment’s single-column key). Ids that are malformed, or encoded for another node type, fail the request before your method runs. `override: false plus an unresolvable route still fails the build, because the implicit column predicate is then required to compose and there is nothing for it to bind.
What the method owns here is the predicate, not the wire format. That split is what makes the escape usable at all: a @condition class is reflected while the generator runs, so it compiles before the generated NodeIdEncoder exists and could never call it. Decoding in the generated code is also what keeps one rule at the slot: a parameter bound to the whole of a @nodeId slot receives the decoded key at every coordinate, routed or method-owned. (A dotted argMapping: binds something narrower; see the constraints in @condition.)
Mixing the two contracts on one leaf, some branches generator-routed and some method-owned, is rejected at build time. The reason the build has to say so is that nothing downstream would: the two contracts hand the method different tables, and the method is free to accept both, whether it takes a Table<?> parameter or an overload set with one concrete declaration per participant. Either way a split compiles and shows up only as a wrong WHERE at request time; the build names the split participants and the two remedies that work.
A mutation that takes the id of any implementation
The write side of the same shape, and here the decode has to cross into your own code rather than being consumed by a generated query. A @service mutation takes the id of any implementation of an interface as one input field by naming the interface in typeName:, and types the receiving Java slot as something every implementation’s generated record is:
union AddressOccupant = Customer | Staff
input DeactivateOccupantInput {
"The id of a Customer or a Staff."
occupantId: ID! @nodeId(typeName: "AddressOccupant")
}
type Mutation {
deactivateOccupant(input: DeactivateOccupantInput!): Boolean
@service(service: {className: "com.example.OccupantService", method: "deactivate"})
}
public record DeactivateOccupantInput(UpdatableRecord<?> occupantId) {}
public static Boolean deactivate(DeactivateOccupantInput in) {
if (in.occupantId() instanceof CustomerRecord c) {
return deactivateCustomer(c.getCustomerId());
}
if (in.occupantId() instanceof StaffRecord s) {
return deactivateStaff(s.getStaffId());
}
throw new IllegalStateException("unreachable: the fetcher decodes one of the two");
}
A request supplies one opaque id and the generated fetcher decodes it before the service runs:
mutation {
deactivateOccupant(input: {occupantId: "Q3VzdG9tZXI6NA=="})
}
The record’s runtime class is what says which implementation the id belonged to, and its loaded key columns are the key. An id belonging to no implementation fails the request in the same wording the read side gives it, before your method runs:
Invalid node id "RmlsbTo0Mg==" for this argument: decodes to type "Film", expected an id of one of: Customer, Staff
UpdatableRecord<?> is the slot type to reach for when every implementation’s table has a primary key; where one does not, jOOQ generates a TableRecordImpl for it and the slot has to be TableRecord<?>, which the build says. org.jooq.Record works for any candidate set, and an interface your jOOQ configuration’s recordImplements puts on the records works too. Typing the slot as one implementation’s own record is refused: decoding the one and rejecting the others is the single-type spelling, so typeName: should name that type instead.
The same shape works at a top-level @service argument whose producer parameter is named for it, and at a list slot ([ID!] into List<UpdatableRecord<?>>), where each element decodes on its own prefix. What it does not do is reach a read-side coordinate: naming an interface at an output field, or at a filter input or lookup argument of a generated query, is refused, the polymorphic decode being a rule about a slot that hands a record to your code. The read side’s own polymorphic readings are the two sections above.
Query.node and Query.nodes dispatch
The two Relay entry points are emitted automatically when at least one @node type is classified for the schema:
type Query {
node(id: ID!): Node
nodes(ids: [ID!]!): [Node]
}
Query.node(id:) peeks the typeId via NodeIdEncoder.peekTypeId(id), dispatches through the entity-fetcher table for that type, and SELECT`s the requested fields plus a synthetic `typename column. The Node TypeResolver reads typename to route the row at scatter time. A null ID, an ID of a type this subgraph does not serve, and an ID naming no row return null; an ID that is not base64 of <typeId>:<key>, or whose key does not decode for its type, is the client error.
Query.nodes(ids:) is the batched form. The dispatcher groups IDs by typeId, fans out one batched SELECT per type (DataLoader-backed so siblings sharing a typeId collapse into one round trip), and scatters rows back to each request’s original positions. Mixing Customer, Address, and Film IDs in one call still produces just three queries.
Both entry points only project the fields the client actually selects. The framework knows the type’s table from @node, so the projection respects @field(name:) aliases, @reference joins, and the rest of the directive surface uniformly.
Constraints and pitfalls
-
@noderequires the type to also carry@tableand to implement theNodeinterface. The build rejects bare@nodeand@nodeon non-Node-implementing types. -
@nodeitself is optional when the bound jOOQ class publishesNODE_TYPE_ID/NODE_KEY_COLUMNS:implements Node @table(name: "x")is a complete node declaration and takes both values from the catalog.@tableplus metadata without the interface is still an ordinary table type. -
id: ID!is required on every node type, but@nodeIdon it is not: the field satisfying theNodeinterface is a node ID by construction. When the bound table also has a column literally namedid, the field is ambiguous between the encoded global ID and that column, and the build fails until you say which: write@nodeIdfor the global ID, or@field(name: "id")to expose the raw column instead. -
keyColumns:must form a primary key or another unique key. Reordering the columns changes the ID’s wire format; treat the order as part of the public contract. -
typeId:collisions across types are rejected at build time. If you need two GraphQL types to share a backing table, give each a distincttypeId. -
@nodeIdis a binding directive, not a projection. The slot’s GraphQL type must beID!,ID,[ID!], or[ID!]!. -
On argument decode, an ID’s embedded
typeIdmust match the declaredtypeName:; mismatches fail the request. OnQuery.node/Query.nodes, an ID of a type this subgraph does not serve returnsnull. -
An ID whose key value is not exactly the text graphitron writes for a value of its column (non-numeric, out of range or precision, padded or reformatted) is malformed, on every surface: a client error on
node,nodesand an argument,nullon_entities. Hand-built IDs must spell each key value the way the column’s Java type prints it. -
A key column behind a jOOQ converter round-trips through its Java type. For the built-in value types (dates, times, numbers, strings, UUIDs) the ID decodes to exactly the value it was minted from, including a time of day on an Oracle
DATEmapped toLocalDateTime. For a converter to your own class, the ID decodes only if your converter’s database-side text matches the class’stoString(); otherwise the ID is refused as malformed. Either way a key column’s converter must take every value the column holds to the database type and back unchanged. A converter narrower than the column’s read path, such as a jOOQBindingwhoseconverter()goes throughLocalDatewhile its read keeps the time of day, makes the IDs of the rows whose value it changes decode as malformed (a client error onnode,nodesand an argument,nullon_entities); the server logs a warning naming the column the first time it refuses such an ID. -
On a same-table
@nodeIdargument,@lookupKeyis implicit; the rewrite emits theVALUES-join shape automatically. Explicit@lookupKeyis permitted but redundant.
See also
-
@nodeconfigures the owning type (typeId,keyColumns). -
@nodeIdmarks each encode/decode slot. -
@referencesupplies the FK path for cross-type IDs. -
@lookupKeyis the dispatch path for[ID!]-keyed argument lookups; same-table NodeId arguments imply it. -
How-to: Batch lookups covers the broader
@lookupKeypatterns including non-NodeId keys.