Video in progress

Strong Middle 🧩 Microservices

What happens if you write blocking code in a Spring Cloud Gateway filter?

Spring Cloud Gateway (the WebFlux variant) runs on the Netty event loop, and there are very few threads, by default the number of cores (at least 4). A blocking call in one filter (JDBC, RestTemplate, Thread.sleep) stalls the event loop and slows down the whole gateway.

📖 Answer

By default Reactor Netty creates one event loop thread per CPU core (at least 4). On a 4-core pod that is 4 threads serving thousands of connections. If one of them blocks for 200 ms on a JDBC query, every connection on that thread waits 200 ms. Under load this shows up as p99 latency spikes and eventually timeouts.

A typical mistake is checking an API key against the DB:

// bad: JDBC on the event loop
public Mono<Void> filter(ServerWebExchange ex, GatewayFilterChain chain) {
    boolean ok = apiKeyRepository.existsByKey(key(ex)); // blocks
    return ok ? chain.filter(ex) : reject(ex);
}

Solutions:

  • a reactive client (R2DBC, reactive Redis, WebClient);
  • forcing the blocking code onto a separate pool: Mono.fromCallable(...).subscribeOn(Schedulers.boundedElastic());
  • caching the result of the check.

To find this, the BlockHound library is useful: in a test it reports a blocking call on the event loop with an exception.

Another option: Spring Cloud Gateway now has a Server MVC variant (servlet-based, works well with virtual threads). If the team isn't used to writing reactive code, choosing it reduces mistakes.