GraphQL
Federation
Make this service one part of a larger, combined GraphQL API.
When a company has many teams, one big GraphQL server becomes a bottleneck. Federation (Apollo Federation) splits the graph: each team runs a subgraph that owns its part, and a gateway (Apollo Router) combines them into one API for clients.
A client asks { product(id: 1) { name reviews { text } } }. The gateway asks products for the name and reviews for the reviews, then merges. For that, the reviews subgraph must be able to say "give me product 42" to the products subgraph: this is an entity.
Make this application a subgraph
useGraphQL {
federation = true
schema = """
type Product @key(fields: "id") { id: ID! name: String! price: Long }
type Query { topProducts: [Product!]! }
"""
}
@Resolver
class ProductsResolver(private val products: ProductRepository) {
@Query fun topProducts(): List<Product> = products.top()
@ResolveReference("Product") // how to load a Product from its key
fun reference(id: String): Product? = products.find(id)
}@key(fields: "id")says "Product is an entity, identified byid".@ResolveReference("Product")is called when the gateway sends a representation{ "__typename": "Product", "id": "42" }; its parameters bind by name to the key fields. Return the entity, ornull.
Kest adds the federation fields for you: _service { sdl } (the gateway reads your schema from it) and _entities(representations: [_Any!]!), and declares the federation directives (@key, @extends, @external, @requires, @provides, @shareable).
The other side: extending an entity
The reviews subgraph does not own Product, it adds a field to it:
useGraphQL {
federation = true
schema = """
type Product @key(fields: "id") @extends { id: ID! @external reviews: [Review!]! }
type Review { id: ID! text: String! }
type Query { _unused: Boolean }
"""
}
@Resolver
class ReviewsResolver(private val reviews: ReviewRepository) {
@ResolveReference("Product") fun product(id: String): Map<String, Any?> = mapOf("id" to id) // a stub: only the key is known here
@ResolveField("Product") fun reviews(product: Map<String, Any?>): List<Review> = reviews.forProduct(product["id"] as String)
}Limits (honest)
- This is the subgraph side only: it was tested with Kest's own
_serviceand_entitiesqueries, not against a real Apollo gateway or Router. Try it withrover devor the Router before depending on it. - Entities are loaded one at a time (no batching of representations yet).
- Composition features beyond
@key(@requires,@provideslogic) are declared but need your own resolvers. - Use federation when you really have several teams or services. For one application, plain GraphQL is simpler.