学习教程
Federation

GraphQL 联邦

¥GraphQL federation

微服务是传统单体架构的另一种设计方法,它强调将复杂系统分解为更小、独立管理的组件。在某些方面,GraphQL 联邦就像 GraphQL 的微服务 - 这种架构模式在 GraphQL 生态系统中引起了特别的共鸣。

¥An alternative design approach to the classical monolith, often described as microservices, emphasizes breaking down complex systems into smaller, independently managed components. In some ways, GraphQL federation is like microservices for GraphQL - an architectural pattern that has found particular resonance in the GraphQL ecosystem.

GraphQL 联邦在 Apollo GraphQL 于 2019 年引入了 Apollo Federation 之后得到了广泛的采用。它们的实现已成为 GraphQL 社区的参考点,有助于将联邦模式确立为在 GraphQL 生态系统中构建分布式图的标准架构模式。

¥GraphQL federation gained widespread adoption after Apollo GraphQL introduced Apollo Federation in 2019. Their implementation has become a reference point for the GraphQL community, helping establish federation as a standard architectural pattern for building a distributed graph in the GraphQL ecosystem.

随着越来越多的公司和开发者认识到使用联邦构建分布式 GraphQL 架构的优势,GraphQL 生态系统正在朝着联邦模式标准化的方向发展。GraphQL 基金会的 复合模式工作组 团队由来自业内各个组织的工程师组成,包括 Apollo GraphQLChilliCreamGraphileHasuraNetflix公会,目前正在积极构建 GraphQL Federation 的官方规范。这项工作旨在标准化 GraphQL 服务在分布式系统中的组合和执行方式,同时确保创新和不同实现的空间。

¥With more companies and developers seeing the benefits of building a distributed GraphQL schema with federation, the GraphQL ecosystem is now moving towards standardization of federation patterns. The GraphQL Foundation’s Composite Schema Working Group, which includes engineers from various organizations across the industry including Apollo GraphQL, ChilliCream, Graphile, Hasura, Netflix and The Guild, is actively working on creating an official specification for GraphQL Federation. This effort aims to standardize how GraphQL services can be composed and executed across distributed systems, while ensuring room for innovation and different implementations.

什么是联邦?

¥What is federation?

从架构上讲,联合是一种组织和管理分布式系统的方法。联合的核心是允许自主组件在保持独立性的同时协同工作。可以将其想象成一个联邦政府系统:各个国家在维护其主权的同时,在中央权威机构的领导下就共同关心的问题进行合作。

¥Architecturally, federation is an approach to organizing and managing distributed systems. At its core, federation allows autonomous components to work together while maintaining their independence. Think of it like a federal government system: individual states maintain their sovereignty while cooperating under a central authority for shared concerns.

在软件架构中,联邦使组织能够:

¥In software architecture, federation enables organizations to:

  • 在独立团队之间分配责任

    ¥Distribute responsibility across independent teams

  • 扩展不同的组件独立地

    ¥Scale different components independently

  • 在不同字段之间保持清晰的界限

    ¥Maintain clear boundaries between different domains

  • 实现自主开发和部署

    ¥Enable autonomous development and deployment

  • 减少单点故障

    ¥Reduce single points of failure

想想你在网站上看到的 “使用 Google 登录” 或 “使用 Facebook 登录” 按钮。这就是联邦模式的实际应用:你可以使用你的 Google 或 Facebook 账户登录许多不同的网站,即使每个公司都分别管理自己的登录系统。

¥Think of the “Login with Google” or “Login with Facebook” buttons you see on websites. This is federation in action: you can use your Google or Facebook account to log into many different websites, even though each company manages their own login system separately.

什么是联邦 GraphQL?

¥What is federated GraphQL?

GraphQL 联邦将这些原则应用于 GraphQL API。它使组织能够从多个独立服务(通常称为子图)构建统一的 GraphQL 模式,每个服务负责应用数据图的各自部分。

¥GraphQL federation applies those principles to GraphQL APIs. It enables organizations to build a unified GraphQL schema from multiple independent services (most often called subgraphs), each responsible for its portion of the application’s data graph.

设想一个电商平台:你可能有单独的团队来管理产品、用户账户和订单处理。借助 GraphQL 联邦,每个团队可以:

¥Consider an e-commerce platform: You might have separate teams managing products, user accounts, and order processing. With GraphQL federation, each team can:

  • 定义自己的 GraphQL 模式

    ¥Define their own GraphQL schema

  • 独立部署和扩展服务

    ¥Deploy and scale their service independently

  • 为统一的 GraphQL API 做出贡献,且无需紧密耦合

    ¥Contribute to a unified GraphQL API without tight coupling

  • 维护各自字段特定逻辑的所有权

    ¥Maintain ownership of their domain-specific logic

神奇的事情发生在联邦网关上,它充当中央协调器,将这些独立的模式组合成客户端可以查询的统一模式。

¥The magic happens through a federated gateway that acts as the central coordinator, composing these separate schemas into a unified schema that clients can query.

GraphQL 联邦的工作原理

¥How federation works in GraphQL

联邦过程包含几个关键组件:

¥The federation process involves several key components:

  • 子图:定义自己的 GraphQL 模式和解析器的独立服务

    ¥Subgraphs: Individual services that define their own GraphQL schemas and resolvers

  • 网关:位于客户端和联合服务之间的专用服务

    ¥Gateway: A specialized service that sits between clients and your federated services

  • 模式组合:合并模式并解析它们之间的引用的过程,通常由模式注册表处理。

    ¥Schema composition: The process of merging schemas while resolving references between them, often handled by schema registries.

type Product @key(fields: "id") {
  id: ID!
  title: String!
  price: Float!
  inStock: Boolean!
}

Schema 组合

¥Schema composition

让我们通过更详细和示例来分解 GraphQL 联邦中的模式组合。模式组合是将多个子图模式组合成一个统一模式的过程。不过,这比简单地合并模式要复杂得多,因为它需要处理关系、检测不兼容性,并确保跨服务和子图的类型正确连接。

¥Let’s break down schema composition in GraphQL federation with more detail and examples. Schema composition is the process where multiple subgraph schemas are combined into one unified schema. It’s more complex than simply merging schemas together, though, because it needs to handle relationships, detect incompatibilities, and ensure types are properly connected across services and subgraphs.

基于我们之前提供的示例,GraphQL 客户端将看到并可以查询的统一模式如下:

¥Based on the examples we provided before, here’s the unified schema GraphQL clients will see and can query:

type Query {
  user(id: ID!): User
}
 
type User {
  id: ID!
  name: String!
  email: String
  orders: [Order!]!
}
 
type Order {
  id: ID!
  products: [Product!]!
  total: Float!
}
 
type Product {
  id: ID!
  title: String!
  price: Float!
  inStock: Boolean!
}

这个统一的 Schema 组合了所有三个子图(用户、订单和产品)的类型和字段,允许客户端跨这些域进行无缝查询。

¥This unified schema combines types and fields from all three subgraphs (Users, Orders, and Products), allowing clients to seamlessly query across these domains.

网关

¥Gateway

联邦网关是分布式数据图的入口点。它向客户端提供统一的 GraphQL 端点,并处理将查询路由到适当子图并组装结果的复杂性,并且通常提供缓存和性能优化。

¥The federation gateway is the entry point to your distributed data graph. It presents a unified GraphQL endpoint to clients and handles the complexity of routing queries to the appropriate subgraphs and assembling the results, and often provides caching and performance optimizations.

以以下查询为例:

¥Take the following query as an example:

query {
  user(id: "123") {
    # Resolved by Users subgraph
    name
    orders {
      # Resolved by Orders subgraph
      id
      products {
        # Resolved by Products subgraph
        title
        price
      }
    }
  }
}

网关会将查询的各个部分路由到相应的子图,收集结果,并将它们组合成客户端可以使用的单个响应。

¥The gateway will route parts of the query to the appropriate subgraphs, collect the results, and assemble them into a single response that the client can consume.

GraphQL 联邦的优势

¥Benefits of GraphQL federation

字段驱动开发

¥Domain-driven development

团队可以独立开发各自的服务,同时为构建一个统一的 API 做出贡献。这种自主性可以加速开发并减少协调开销。

¥Teams can work independently on their services while contributing to a cohesive API. This autonomy accelerates development and reduces coordination overhead.

服务完整性保护

¥Service integrity protection

Schema 组合步骤通过确保各个子图中的更改不会与其他子图冲突来验证服务之间的集成。

¥The schema composition step verifies integration between services by ensuring that changes in individual subgraphs do not conflict with other subgraphs.

可扩展性和性能

¥Scalability and performance

子图和服务可以根据其特定需求独立扩展。产品目录可能需要与订单处理系统不同的扩展特性。

¥Subgraphs and services can be scaled independently based on their specific requirements. The product catalog might need different scaling characteristics than the order processing system.

单一、统一的 API

¥Single, unified API

借助 GraphQL,客户端可以获得一个具有跨多个子图的统一模式的端点。分布式系统的复杂性被隐藏了。网关确保每个查询都到达目的地并返回正确的数据。

¥Thanks to GraphQL, clients get a single endpoint with unified schema spanning multiple subgraphs. The complexity of distributed systems is hidden. The gateway ensures every query reaches its destination and returns with the right data.

GraphQL 联邦适合你吗?

¥Is GraphQL federation right for you?

GraphQL 联邦与字段驱动设计 (DDD) 原则自然契合,它允许团队在其字段内维护清晰的边界,同时通过 GraphQL 模式维护明确的集成点。对于多个团队需要独立处理 GraphQL API 不同部分的组织来说,它尤其有价值,并且可以灵活地使用不同的技术和编程语言。

¥GraphQL federation aligns naturally with Domain Driven Design (DDD) principles by allowing teams to maintain clear boundaries around their domains, while maintaining explicit integration points through the GraphQL schema. It is particularly valuable for organizations where multiple teams need to work independently on different parts of the GraphQL API, with the flexibility to use different technologies and programming languages.

然而,实现联邦需要大量的基础设施支持,包括专门的团队来管理网关、模式注册表,以帮助将子图连接到联邦 API,并指导团队采用最佳实践。

¥However, implementing federation requires substantial infrastructure support, including a dedicated team to manage the gateway, schema registry, to help connect subgraphs to the federated API and guide teams on best practices.

在采用联邦之前,务必考虑你的组织是否真正需要这种复杂程度。你可以从单体设置开始,然后随着需求的变化过渡到联邦,而不是过早地实现。

¥Before adopting federation, it’s crucial to consider whether your organization truly needs this level of complexity. You can start with a monolithic setup and transition to federation as your needs evolve, rather than implementing it prematurely.

Meta(前身为 Facebook)GraphQL 的诞生地 自 2012 年以来一直使用单体 GraphQL API。然而,像 NetflixExpedia 集团沃尔沃预订 这样的公司已经采用了联邦,以便更好地与其组织结构和微服务架构保持一致。

¥Meta (formerly Facebook), where GraphQL was created, has continued to use a monolithic GraphQL API since 2012. However, companies like Netflix, Expedia Group, Volvo, and Booking have adopted federation to better align with their organizational structures and microservices architecture.

正如你所见,一些全球最大的行业领导者已经成功联合了他们的 GraphQL API,证明了它在超大规模的生产应用中能够可靠地运行。

¥As you see, some of the world’s largest industry leaders have successfully federated their GraphQL APIs, proving that it works reliably for production applications at an extraordinary scale.

GraphQL 联邦入门

¥Getting started with GraphQL federation

如果你正在考虑采用 GraphQL 联邦,请按照以下步骤开始:

¥If you’re considering adopting GraphQL federation, here are some steps to get started:

  1. 识别服务边界:在应用中的不同域之间明确定义边界

    ¥Identify Service Boundaries: Define clear boundaries between different domains in your application

  2. 设计模式:创建能够反映这些边界的模式,同时考虑它们之间的交互方式

    ¥Design Schemas: Create schemas that reflect these boundaries while considering how they’ll interact

  3. 实现子图:构建单独的服务来实现其对应的模式部分

    ¥Implement Subgraphs: Build individual services that implement their portion of the schema

  4. 设置网关:部署联邦网关来编写并提供统一模式

    ¥Set Up a Gateway: Deploy a federation gateway to compose and serve the unified schema

  5. 使用模式注册表:管理模式组合和验证,以确保跨子图的完整性

    ¥Use a Schema Registry: Manage schema composition and validation to ensure integrity across subgraphs

从单体 GraphQL API 迁移到联邦 GraphQL API 时,最简单的起点是将现有架构视为第一个子图。之后,你可以按照上述步骤逐步将模式分解为更小的部分。

¥When migrating from a monolithic to federated GraphQL API, the simplest starting point is to treat your existing schema as your first subgraph. From there, you can follow the steps above to gradually decompose your schema into smaller pieces.