wasAsked.

How do you protect a Java service from slow dependencies using timeouts, retries, bulkheads, and circuit breakers?

Zomato · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Microservices, Software Engineering

Community answers

Posted by wasAsked editorial collection

Slow dependencies are more dangerous than failing ones, because they tie up threads and connections until the whole service stalls. Use several patterns together. Timeouts (first and most important) - Set connect and read timeouts on every outbound call: RestClient or WebClient with configured HTTP client timeouts, Feign client options, and JDBC query timeouts. - Set an overall time budget per operation (Resilience4j TimeLimiter, or CompletableFuture.orTimeout). - Never rely on defaults — some HTTP clients wait indefinitely. Retries - Retry only transient errors (connection resets, 503, 429, timeouts) and only idempotent operations, or use idempotency keys. - Exponential backoff with jitter, a small maximum number of attempts, and respect for Retry-After. - Count retries in the overall time budget, otherwise retries multiply latency and load (retry storms). Bulkheads - Isolate resources per dependency so one slow service cannot consume everything: Resilience4j Bulkhead (semaphore-based concurrency limit) or ThreadPoolBulkhead (separate thread pool). - Separate connection pools per downstream service. With virtual threads, limit concurrency per dependency with semaphores. Circuit breakers - Resilience4j CircuitBreaker opens after a failure-rate or slow-call-rate threshold (for example 50% of the last 20 calls failing or slower than 2 seconds), then fails fast for a wait period, and tests recovery with a few calls in half-open state. @CircuitBreaker(name = "pricing", fallbackMethod = "cachedPrice") @Retry(name = "pricing") @Bulkhead(name = "pricing") public Price getPrice(String sku) { return pricingClient.get(sku); } private Price cachedPrice(String sku, Throwable t) { return priceCache.getLastKnown(sku); } Configure the instances in application.yml (thresholds, wait durations, retry backoff). Fallbacks and degradation - Return cached or default data, hide the optional feature, or queue the work for later processing. Asynchronous decoupling - For non-urgent work, publish an event or message instead of calling synchronously, so the dependency's slowness does not affect user requests. Observability and testing - Export Resilience4j metrics (Micrometer) for circuit states, retries and bulkhead rejections; alert on open circuits. - Test with fault injection: WireMock with delays and error responses, Toxiproxy, or chaos experiments. Order of decorators matters: typically retry wraps the circuit breaker, which wraps the time limiter and bulkhead — follow Resilience4j's documented ordering and verify behaviour in tests.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics