0
0
GraphqlHow-ToBeginner · 4 min read

How to Use @key Directive in Federation in GraphQL

In GraphQL federation, use the @key directive to specify one or more fields that uniquely identify an entity across services. This directive enables the gateway to resolve and reference entities correctly when composing multiple GraphQL services into a single graph.
📐

Syntax

The @key directive is placed on a GraphQL type to declare the primary key fields that uniquely identify an entity. It accepts a fields argument, which is a string listing one or more fields (including nested fields) that form the unique key.

  • @key(fields: "fieldName"): Defines a single field as the key.
  • @key(fields: "field1 field2"): Defines a composite key using multiple fields.
  • The fields must be part of the type and uniquely identify the entity.
graphql
type Product @key(fields: "upc") {
  upc: String!
  name: String
  price: Int
}
💻

Example

This example shows two federated services sharing the Product entity. The @key directive on Product declares upc as the unique identifier. The gateway uses this to fetch and combine data from both services.

graphql
### Service A: Product Service

extend type Product @key(fields: "upc") {
  upc: String! @external
  name: String
}

### Service B: Review Service

type Product @key(fields: "upc") {
  upc: String!
  reviews: [Review]
}

type Review {
  id: ID!
  body: String
}
Output
Gateway can resolve Product entities by their 'upc' field across services, merging 'name' and 'reviews' data.
⚠️

Common Pitfalls

  • Not marking the key fields as @external in extended types causes errors because the field is missing locally.
  • Using fields in @key that are not unique or not present in the type leads to incorrect entity resolution.
  • For composite keys, forgetting to include all key fields in the fields argument causes federation failures.
graphql
### Wrong usage (missing @external):

extend type Product @key(fields: "upc") {
  upc: String!  # Missing @external here
  reviews: [Review]
}

### Correct usage:

extend type Product @key(fields: "upc") {
  upc: String! @external
  reviews: [Review]
}
📊

Quick Reference

DirectivePurposeNotes
@key(fields: "field")Defines unique identifier fields for an entityFields must exist and uniquely identify the entity
@externalMarks fields as owned by another serviceRequired on key fields in extended types
@extendsIndicates the type is extended from another serviceUsed with @key on extended types

Key Takeaways

Use @key to declare unique fields that identify an entity across federated services.
Mark key fields as @external in extended types to avoid schema errors.
Composite keys require listing all key fields in the @key directive.
The gateway uses @key fields to fetch and merge entity data from multiple services.
Incorrect or missing @key usage breaks entity resolution in federation.