GraphQL APIs with Spring Boot · Lezione

Limitazione della frequenza e protezione dalla profondità delle query

Protegga l'API GraphQL Spring Boot da abusi e attacchi denial-of-service limitando la frequenza delle chiamate dei client e la profondità di annidamento delle query.

Lezione 4 di 413 passaggi

Limitazione della frequenza e protezione dalla profondità delle query è una lezione GraphQL APIs with Spring Boot gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento GraphQL APIs with Spring Boot, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso GraphQL APIs with Spring Boot include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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.

Gratis per iniziare

Impara GraphQL APIs with Spring Boot con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
12
Lezioni
48

Domande Frequenti

La lezione «Limitazione della frequenza e protezione dalla profondità delle query» è gratuita?

Sì — il testo completo di «Limitazione della frequenza e protezione dalla profondità delle query» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso GraphQL APIs with Spring Boot, passa a CoddyKit PRO. Il corso GraphQL APIs with Spring Boot include 4 lezioni in totale.

Cosa imparerò in «Limitazione della frequenza e protezione dalla profondità delle query»?

Protegga l'API GraphQL Spring Boot da abusi e attacchi denial-of-service limitando la frequenza delle chiamate dei client e la profondità di annidamento delle query. Eserciti GraphQL APIs with Spring Boot con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare GraphQL APIs with Spring Boot?

Non è richiesta alcuna esperienza precedente. GraphQL APIs with Spring Boot su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Limitazione della frequenza e protezione dalla profondità delle query»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione GraphQL APIs with Spring Boot?

Sì. Ogni lezione GraphQL APIs with Spring Boot include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Gestione personalizzata degli errori in GraphQL
  2. Autenticazione con Spring Security
  3. Autorizzazione con direttive e contesto
  4. Limitazione della frequenza e protezione dalla profondità delle query
← Torna a GraphQL APIs with Spring Boot