Détection des appels bloquants en WebFlux

VérifiéSûr

Identifiez les appels bloquants dans le code réactif Spring WebFlux qui causent la privation de threads et dégradation des performances.

Spar Skills Guide Bot
DeveloppementIntermédiaire
01/03/2026
Claude CodeCursorCodex
#reactive#webflux#performance#java#code-review

Recommandé pour

Synthèse automatique

Repère dans un codebase Spring WebFlux les appels bloquants (.block(), Thread.sleep, I/O bloquante, JDBC) susceptibles de provoquer une famine de threads ou des ralentissements.

Points forts

  • Liste de motifs à rechercher très concrète : blocage direct sur Mono/Flux, verrous, I/O, JDBC/JPA.
  • Analyse contextuelle qui distingue le blocage acceptable (StructuredTaskScope, @Scheduled, tests, boundedElastic) du blocage problématique sur l'event loop.
  • Couvre les anti-patterns réactifs classiques comme un appel bloquant dans map ou flatMap, avec le correctif attendu.
  • Prend en compte les virtual threads de Java 24 et les appels OkHttp du projet.

Limites

  • Analyse purement textuelle via Grep : aucun profilage runtime ni détection réelle du thread event loop.
  • Résultats potentiellement bruyants, des motifs comme synchronized, .get() ou .save() remontent hors contexte.
  • Les règles « acceptables » citées sont propres à un projet donné et doivent être adaptées ailleurs.
Quand l'utiliser

À utiliser lors d'une revue de code réactif ou d'un diagnostic de performances sur une application Spring WebFlux existante.

Quand l'éviter

À éviter sur du code impératif classique, sur un projet non Spring/WebFlux, ou si vous cherchez une mesure de performance réelle plutôt qu'un audit statique.

Analyse de sécurité

Sûr
Score qualité90/100

The skill provides static analysis guidance for identifying blocking calls in reactive code. It does not instruct any destructive actions, data exfiltration, or execution of commands. It only advises using Grep and manual review, posing no execution risk.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Audit of a WebFlux service
Scan our Spring WebFlux modules for blocking calls that could starve the Netty event loop, and list each finding with its file, line and whether it's acceptable or problematic.
Reactive chain anti-patterns
Check the controllers and services under src/main/java for blocking calls inside map or flatMap operators and show me the boundedElastic fix for each one.
Virtual thread exceptions
Find every .block() call in this project and tell me which ones run inside StructuredTaskScope or virtual threads and are therefore fine to keep.

name: profile-blocking description: Find blocking calls in reactive WebFlux code that can cause performance issues and thread starvation

Profile Blocking Skill

Identify blocking calls in the reactive codebase that can cause thread starvation, deadlocks, and performance degradation in Spring WebFlux applications.

Instructions

1. Search for Blocking Patterns

Use Grep to search for these blocking call patterns:

Direct Blocking Calls

.block()           // Mono/Flux blocking subscription
.blockFirst()      // Flux blocking first element
.blockLast()       // Flux blocking last element
.blockOptional()   // Mono blocking to Optional
.toFuture().get()  // CompletableFuture blocking
.get()             // Future.get() blocking
.join()            // CompletableFuture.join()

Thread Blocking

Thread.sleep(      // Thread sleep
Object.wait(       // Object monitor wait
.await(            // CountDownLatch, CyclicBarrier await
.acquire(          // Semaphore blocking acquire
synchronized       // Synchronized blocks (potential)
ReentrantLock.lock // Explicit locking

Blocking I/O

InputStream        // Blocking input streams
OutputStream       // Blocking output streams
FileInputStream    // File I/O
FileOutputStream   // File I/O
BufferedReader     // Blocking readers
Scanner            // Blocking scanner
new URL(           // URL.openStream() is blocking
HttpURLConnection  // Blocking HTTP

JDBC/Database (if present)

JdbcTemplate       // Blocking JDBC
EntityManager      // Blocking JPA
.save(             // Repository blocking save
.findBy            // Repository blocking find
DataSource         // Direct datasource access

2. Context-Aware Analysis

For each finding, determine if it's:

Acceptable blocking:

  • Inside StructuredTaskScope (this project uses Java 24 virtual threads)
  • In @Scheduled methods running on separate thread pool
  • In test code
  • Wrapped in Mono.fromCallable() with .subscribeOn(Schedulers.boundedElastic())
  • In startup/initialization code (non-request path)

Problematic blocking:

  • In @RestController methods returning Mono/Flux
  • In reactive chain operators (map, flatMap, filter)
  • On Netty event loop threads
  • In WebFilter implementations
  • Inside Mono.create() or Flux.create() without scheduler

3. Analyze Reactive Chains

Check for anti-patterns in reactive code:

// BAD: Blocking in map
mono.map(data -> {
    blockingCall();  // Blocks event loop!
    return result;
})

// BAD: Blocking in flatMap
flux.flatMap(item -> {
    var result = blockingService.call();  // Blocks!
    return Mono.just(result);
})

// GOOD: Proper offloading
mono.flatMap(data ->
    Mono.fromCallable(() -> blockingCall())
        .subscribeOn(Schedulers.boundedElastic())
)

4. Check This Project's Specific Patterns

Files to examine:

  • src/main/java/**/controller/*.java - REST endpoints
  • src/main/java/**/service/*.java - Service layer
  • src/main/java/**/strategy/*.java - Strategy implementations
  • src/main/java/**/config/*.java - Configuration classes

Known acceptable patterns in this project:

  • StructuredTaskScope usage in AggregatorService (virtual threads)
  • .block() inside virtual thread contexts
  • OkHttp calls (executed in separate thread pool)

Patterns to flag:

  • .block() in controller methods
  • Blocking in WebFilter or HandlerFilterFunction
  • Synchronous HTTP calls without proper scheduling

5. Virtual Thread Considerations

This project uses Java 24 with virtual threads. Check:

// Virtual thread factory usage
Thread.ofVirtual().factory()

// StructuredTaskScope usage (blocking is OK inside)
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    scope.fork(() -> blockingCall());  // OK - virtual thread
    scope.join();  // OK - virtual thread blocks, not platform thread
}

6. HTTP Client Analysis

Check OkHttp usage patterns:

// Synchronous call - check if on reactive thread
Response response = client.newCall(request).execute();

// Better: Use async
client.newCall(request).enqueue(callback);

// Or wrap properly
Mono.fromCallable(() -> client.newCall(request).execute())
    .subscribeOn(Schedulers.boundedElastic())

Output Format

## Blocking Call Analysis Report

### Summary
| Category | Count | Severity |
|----------|-------|----------|
| Direct .block() calls | X | High/Medium |
| Thread.sleep() | X | High |
| Blocking I/O | X | Medium |
| Synchronized blocks | X | Low |
| **Total potential issues** | **Y** | |

### Critical Issues (Event Loop Blocking)

#### [Issue Title]
**File**: `path/to/file.java:line`
**Pattern**: `.block()` in reactive chain
**Context**: Inside @RestController endpoint
**Risk**: Thread starvation, request timeouts
```java
// Current code
@GetMapping("/data")
public Mono<Data> getData() {
    return service.fetchData()
        .map(d -> blockingTransform(d));  // BLOCKS!
}

Fix:

@GetMapping("/data")
public Mono<Data> getData() {
    return service.fetchData()
        .flatMap(d -> Mono.fromCallable(() -> blockingTransform(d))
            .subscribeOn(Schedulers.boundedElastic()));
}

Medium Priority (Potential Issues)

| File | Line | Pattern | Context | Verdict | |------|------|---------|---------|---------| | Service.java | 42 | .block() | Inside StructuredTaskScope | OK | | Handler.java | 78 | Thread.sleep | Test code | OK |

Acceptable Blocking (Verified Safe)

These blocking calls are in appropriate contexts:

| File | Line | Pattern | Why It's OK | |------|------|---------|-------------| | AggregatorService.java | 120 | .block() | Inside virtual thread scope | | ForecastService.java | 85 | OkHttp.execute() | Wrapped in fromCallable |

Patterns Found

.block() Calls

src/main/java/.../Service.java:42  - response.block()
src/main/java/.../Service.java:87  - result.blockFirst()

Thread Blocking

src/main/java/.../Worker.java:23   - Thread.sleep(1000)

Blocking I/O

src/main/java/.../Reader.java:15   - new FileInputStream()

Recommendations

  1. Immediate: Move blocking call at File.java:42 to bounded elastic scheduler
  2. Review: Verify StructuredTaskScope usage covers all blocking in AggregatorService
  3. Consider: Replace synchronous OkHttp with async calls or WebClient

Reactive Best Practices Checklist

  • [ ] No .block() in @RestController methods
  • [ ] No .block() in WebFilter implementations
  • [ ] Blocking I/O wrapped with boundedElastic scheduler
  • [ ] Thread.sleep() only in tests or scheduled tasks
  • [ ] Synchronized blocks minimized and not in hot paths
  • [ ] HTTP clients properly configured for async or offloaded

## Execution Steps

1. Use `Grep` to find all `.block()` calls
2. Use `Grep` to find `Thread.sleep`, `.await(`, `synchronized`
3. Use `Grep` to find blocking I/O patterns
4. Read each file to determine context (controller vs service vs test)
5. Check if blocking is inside StructuredTaskScope or virtual thread
6. Categorize findings by severity
7. Generate report with fix recommendations

## Notes

- Virtual threads (Java 21+) change the blocking calculus - blocking is OK on virtual threads
- This project uses StructuredTaskScope, so verify scope boundaries
- OkHttp is blocking by default but may be acceptable if not on event loop
- Focus on request-handling paths; scheduled tasks are lower priority
- Some `.block()` in tests is normal and acceptable
- Spring WebFlux Netty uses limited event loop threads - blocking them is critical

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/profile-blocking-calls-in-webflux-mm78nodg/download' --output '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md.part' && mv '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md.part' '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && test -s '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/profile-blocking' && cp -R '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg' '.claude/skills/profile-blocking'

Cursor
test -f '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && test -s '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/profile-blocking' && cp -R '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg' '.cursor/skills/profile-blocking'

Codex
test -f '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && test -s '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/profile-blocking' && cp -R '.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg' '.agents/skills/profile-blocking'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/profile-blocking-calls-in-webflux-mm78nodg'

openskills read 'profile-blocking-calls-in-webflux-mm78nodg'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/profile-blocking-calls-in-webflux-mm78nodg/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires