Ограничение частоты запросов и защита от чрезмерной глубины
Защитите API GraphQL на Spring Boot от злоупотреблений и отказа в обслуживании, ограничивая частоту вызовов клиентов и глубину вложенности их запросов.
«Ограничение частоты запросов и защита от чрезмерной глубины» — бесплатный урок GraphQL APIs with Spring Boot на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения GraphQL APIs with Spring Boot, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why GraphQL Needs Protection
A single GraphQL endpoint accepts arbitrarily complex queries. A malicious or careless client can request deeply nested data or hammer the server, exhausting resources.
Rate limiting and depth protection defend against these attacks.
The Nested Query Threat
Because GraphQL allows cyclic relationships, a client could ask for an author's books, each book's author, that author's books, and so on. This recursion can balloon into an enormous, expensive query.
query {
author {
books { author { books { author { name } } } }
}
}Limiting Query Depth
graphql-java provides MaxQueryDepthInstrumentation, which rejects any query that nests deeper than a set limit before execution begins.
@Bean
public Instrumentation depthLimit() {
return new MaxQueryDepthInstrumentation(10);
}Limiting Field Count
Beyond depth, a broad query can request thousands of fields. MaxQueryComplexityInstrumentation caps the total complexity score of a query.
@Bean
public Instrumentation complexityLimit() {
return new MaxQueryComplexityInstrumentation(200);
}What Is Rate Limiting?
Rate limiting caps how many requests a client may make in a time window. It prevents abuse and ensures fair resource sharing across clients.
The Token Bucket Idea
A common algorithm is the token bucket: each client has a bucket that refills at a steady rate. Every request consumes a token; if the bucket is empty, the request is rejected.
Rate Limiting with Bucket4j
The bucket4j library implements token buckets in Java. Configure a bucket with a refill rate and capacity.
Bandwidth limit = Bandwidth.simple(100, Duration.ofMinutes(1));
Bucket bucket = Bucket.builder().addLimit(limit).build();Enforcing the Limit
Before processing a request, try to consume a token. If none is available, return an error instead of executing the query.
if (!bucket.tryConsume(1)) {
throw new RateLimitException("Too many requests");
}Per-Client Buckets
Track a separate bucket per client, keyed by API key or authenticated user ID, so one heavy client cannot starve everyone else.
Bucket bucket = buckets.computeIfAbsent(userId, k -> newBucket());Combining Defenses
Layer your protections for full coverage:
- Depth limit stops recursive abuse
- Complexity limit stops broad expensive queries
- Rate limit stops request floods
- Timeouts stop slow runaway operations
Best Practices
Tune limits to your real traffic:
- Start strict, then relax based on monitoring
- Return clear errors so clients can back off
- Apply tighter limits to unauthenticated traffic
- Log rejected queries to spot abuse patterns
Quick Check
Test your API protection knowledge.
Recap
You hardened your GraphQL API:
- Depth and complexity instrumentation block expensive queries
- Rate limiting caps request frequency per client
- Token buckets (bucket4j) implement fair limits
- Layer depth, complexity, rate, and timeout defenses
These guards keep your API available and resilient under abuse.
Часто задаваемые вопросы
Урок «Ограничение частоты запросов и защита от чрезмерной глубины» бесплатный?
Да — полный текст урока «Ограничение частоты запросов и защита от чрезмерной глубины» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс GraphQL APIs with Spring Boot, подпишись на CoddyKit PRO. Курс GraphQL APIs with Spring Boot содержит 4 уроков всего.
Чему я научусь в уроке «Ограничение частоты запросов и защита от чрезмерной глубины»?
Защитите API GraphQL на Spring Boot от злоупотреблений и отказа в обслуживании, ограничивая частоту вызовов клиентов и глубину вложенности их запросов. Ты практикуешь GraphQL APIs with Spring Boot с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать GraphQL APIs with Spring Boot?
Предыдущий опыт не требуется. GraphQL APIs with Spring Boot на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Ограничение частоты запросов и защита от чрезмерной глубины»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке GraphQL APIs with Spring Boot?
Да. Каждый урок GraphQL APIs with Spring Boot включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Пользовательская обработка ошибок в GraphQL
- Аутентификация с Spring Security
- Авторизация с директивами и контекстом
- Ограничение частоты запросов и защита от чрезмерной глубины