GraphQL APIs with Spring Boot · Урок

Знакомство с федерацией Apollo

Разберитесь в концепциях федерации GraphQL, её преимуществах для микросервисных архитектур и отличиях от сшивания схем.

Урок 1 из 412 шагов

«Знакомство с федерацией Apollo» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Welcome to Federation

Welcome to Apollo Federation! This powerful architecture helps you build a single, unified GraphQL API from multiple independent microservices.

Imagine having many small services, each responsible for a part of your application. Federation lets them all contribute to one big GraphQL schema.

The Microservices Challenge

In a microservices architecture, you often have different teams managing separate backend services. How do you expose a coherent GraphQL API?

  • Monolithic GraphQL: One big server, hard to scale for large teams.
  • Multiple GraphQL Endpoints: Clients need to query different services, increasing complexity.

Federation offers a clean solution to this challenge.

A Distributed Schema

The core idea of Federation is that different services (called subgraphs) can each define a part of your overall GraphQL schema.

These parts are then combined by a central Gateway into one unified graph. It's like having many contributors to a single, shared blueprint.

Gateway and Subgraphs

Apollo Federation involves two main architectural components:

  • Gateway: This is the entry point for all client requests. It knows about all your subgraphs and how to route queries.
  • Subgraphs: These are your individual microservices. Each subgraph implements a specific part of the GraphQL schema and resolves data for its domain.

How a Federated Query Works

When a client sends a GraphQL query to the Gateway, here's a simplified flow:

  1. The Gateway receives the query.
  2. It analyzes which subgraphs are needed to fulfill the request.
  3. The Gateway breaks down the query and sends specific parts to the relevant subgraphs.
  4. It then combines the results from all subgraphs into a single response for the client.

Why Use Federation?

Federation offers significant advantages for large, evolving systems:

  • Scalability: Teams can develop and deploy subgraphs independently.
  • Decoupling: Services remain autonomous, reducing inter-service dependencies.
  • Unified API: Clients get a single, consistent GraphQL endpoint.
  • Strong Type Safety: The entire graph is strongly typed, even across services.

Federation vs. Schema Stitching (Part 1)

You might have heard of Schema Stitching, another way to combine GraphQL APIs. How does Federation differ?

With Stitching, individual schemas are combined at the Gateway, but the sub-schemas are often unaware of each other. It's more like joining separate documents.

Federation promotes a truly distributed graph where subgraphs explicitly collaborate and extend shared types.

Federation vs. Schema Stitching (Part 2)

The execution model is another key difference:

  • Stitching: The Gateway might fetch data from one service, then another, and manually combine them. This can lead to less optimized data fetching.
  • Federation: The Gateway understands the relationships between types across subgraphs. It can intelligently plan efficient queries, fetching only what's needed from each service.

When to Choose Apollo Federation

Federation is particularly well-suited for:

  • Large organizations with many development teams.
  • Complex microservice architectures that need a unified API.
  • Scenarios where you want to expose a single, evolving GraphQL graph over time.

If you have a smaller, simpler application, a single GraphQL server might suffice.

Federation in Spring Boot

When building federated subgraphs with Spring Boot, you'll define your GraphQL types as usual. However, you'll also use specific Federation directives.

The most important is @key, which identifies an entity's primary key across different subgraphs. This allows the Gateway to understand and resolve relationships.

Test Your Understanding

Let's check your grasp of the core concepts.

Recap & Next Steps

Great job! In this lesson, we introduced Apollo Federation, a powerful approach for building a unified GraphQL API from multiple microservices.

  • We covered the roles of the Gateway and Subgraphs.
  • We explored how Federation enables a distributed schema and efficient query execution.
  • We also saw how it differs from Schema Stitching.

Next, we'll dive into building your first federated subgraphs with Spring Boot!

Можно начать бесплатно

Изучай GraphQL APIs with Spring Boot с ИИ-репетитором — бесплатно

Пиши и запускай код прямо в браузере, получай мгновенную помощь от ИИ-репетитора 24/7 и продолжи учиться на сайте или в приложении.

Курсы
12
Уроки
48

Часто задаваемые вопросы

Урок «Знакомство с федерацией Apollo» бесплатный?

Да — полный текст урока «Знакомство с федерацией Apollo» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.

Чему я научусь в уроке «Знакомство с федерацией Apollo»?

Разберитесь в концепциях федерации GraphQL, её преимуществах для микросервисных архитектур и отличиях от сшивания схем. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?

Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.

Сколько времени занимает урок «Знакомство с федерацией Apollo»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?

Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Знакомство с федерацией Apollo
  2. Создание федеративных подграфов
  3. Настройка и управление шлюзом
  4. Ссылки на сущности и директива @key
← Назад к GraphQL APIs with Spring Boot