<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ahmed Mansour on Medium]]></title>
        <description><![CDATA[Stories by Ahmed Mansour on Medium]]></description>
        <link>https://medium.com/@ahmansour19?source=rss-97e0253031b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*kqFfQfNxw-nZLfzC</url>
            <title>Stories by Ahmed Mansour on Medium</title>
            <link>https://medium.com/@ahmansour19?source=rss-97e0253031b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 07:54:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmansour19/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Optimize Spring RestClient to avoid production bottlenecks]]></title>
            <link>https://medium.com/@ahmansour19/optimize-spring-restclient-to-avoid-production-bottlenecks-038f14c085ce?source=rss-97e0253031b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/038f14c085ce</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Ahmed Mansour]]></dc:creator>
            <pubDate>Sun, 22 Mar 2026 23:02:30 GMT</pubDate>
            <atom:updated>2026-03-22T23:10:09.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Default Spring RestClient settings can slow production systems. This guide shows how to configure pooling, timeouts, and improve performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WKm66TfQA4Yz3LaCaQ-Bfw.png" /></figure><h3>Default behavior</h3><p>By default, RestClient uses SimpleClientHttpRequestFactory backed by Java’s HttpURLConnection. This implementation is functional and requires no setup. However, it lacks capabilities that are critical under load.</p><h3>Core limitation</h3><p>The default request factory does not provide connection pooling.<br>For every HTTP request, the application:</p><ul><li>Opens a new TCP connection</li><li>Performs a TCP handshake</li><li>Performs a TLS handshake (for HTTPS)</li><li>Sends the request</li><li>Closes the connection</li></ul><p>This sequence repeats for every call, regardless of destination.</p><h3>Performance Impact</h3><h4>Connection setup overhead</h4><p>TCP and TLS handshakes introduce measurable latency. Without connection reuse, this cost is paid on every request.</p><h4>Increased latency</h4><p>Even when the target service responds quickly, total request time increases due to connection setup and teardown.</p><h4>Reduced throughput</h4><p>Threads spend more time establishing connections instead of processing responses. This limits the number of requests the system can handle concurrently.</p><h4>Resource inefficiency</h4><p>Repeated connection creation leads to <strong>higher CPU usage, increased memory pressure, and additional network overhead</strong></p><h4>Limited tuning</h4><p>HttpURLConnection provides minimal control over <strong>connection reuse, pool sizing, and advanced timeout strategies</strong></p><p>This restricts the ability to optimize behavior for different external services.</p><h3>Typical production symptoms</h3><ul><li>Acceptable performance in development, degradation under load</li><li>Increased response times as traffic grows</li><li>High CPU usage with modest throughput</li><li>External HTTP calls becoming a bottleneck</li></ul><h3>Recommended approach</h3><p>Use a request factory backed by a client that supports connection pooling, such as Apache HttpClient</p><pre>@Configuration<br>public class RestClientConfig {<br><br>    @Bean<br>    public RestClient restClient() {<br><br>        PoolingHttpClientConnectionManager connectionManager =<br>                new PoolingHttpClientConnectionManager();<br><br>        connectionManager.setMaxTotal(200);<br>        connectionManager.setDefaultMaxPerRoute(50);<br>        connectionManager.setValidateAfterInactivity(TimeValue.ofSeconds(5));<br><br>        RequestConfig requestConfig = RequestConfig.custom()<br>                .setConnectTimeout(Timeout.ofSeconds(3))<br>                .setResponseTimeout(Timeout.ofSeconds(5))<br>                .build();<br><br>        CloseableHttpClient httpClient = HttpClients.custom()<br>                .setConnectionManager(connectionManager)<br>                .setDefaultRequestConfig(requestConfig)<br>                .evictIdleConnections(TimeValue.ofSeconds(30))<br>                .build();<br><br>        HttpComponentsClientHttpRequestFactory requestFactory =<br>                new HttpComponentsClientHttpRequestFactory(httpClient);<br><br>        return RestClient.builder()<br>                .requestFactory(requestFactory)<br>                .baseUrl(&quot;https://api.chemistrylab.com/meth-production&quot;)<br>                .defaultHeader(&quot;X-Restaurant&quot;, &quot;LosPollosHermanos&quot;)<br>                .build();<br>    }<br>}</pre><pre>@Service<br>public class UserService {<br><br>    private final RestClient restClient;<br><br>    public UserService(RestClient restClient) {<br>        this.restClient = restClient;<br>    }<br><br>    public User getUser(Long id) {<br>        return restClient.get()<br>                .uri(&quot;/users/{id}&quot;, id)<br>                .retrieve()<br>                .body(User.class);<br>    }<br>}</pre><p>You don’t pick those values randomly. They should be based on <strong>your traffic, your dependencies, and your infrastructure limits</strong>.</p><h3>How to choose the right configuration values</h3><p>Configuration values for the HTTP client should be derived from <strong>traffic patterns, latency, and system constraints</strong>. Fixed numbers taken from examples are rarely appropriate for production.</p><h4>Connection pool size</h4><p><strong>Total connections</strong></p><p>The total number of connections should reflect how many requests your system needs to handle concurrently.</p><p>A practical way to estimate this:</p><pre>connections ≈ requests_per_second × average_response_time_in_seconds</pre><p><strong>Example</strong></p><ul><li>200 requests per second</li><li>Average response time: 300 ms (0.3 seconds)</li></ul><pre>200 × 0.3 = 60 concurrent connections</pre><p>Add a buffer (20–50%) to handle spikes:</p><pre>≈ 80–100 connections</pre><p><strong>Per-route connections</strong></p><p>This defines how many connections can be used per target host.</p><p>It depends on how your traffic is distributed across external services.</p><p><strong>Example</strong></p><ul><li>Total connections: 200</li><li>4 external services with similar load</li></ul><pre>200 / 4 = 50 connections per service</pre><p>If one service receives most of the traffic, allocate a higher share to that route.</p><h3>Timeouts</h3><p><strong>Connect timeout</strong></p><p>Controls how long the client waits to establish a connection.</p><ul><li>Internal services: 100–500 ms</li><li>External services: 1–3 seconds</li></ul><p>The goal is to fail quickly when a service is unreachable.</p><p><strong>Response timeout</strong></p><p>Controls how long the client waits for a response after the request is sent.</p><p>Set it relative to expected latency:</p><ul><li>Expected latency: 300 ms</li><li>Timeout: around 1 second</li></ul><p>For slower or less predictable services:</p><ul><li>2–5 seconds is typical</li></ul><h4>Idle connection eviction</h4><p>Idle connections should be cleaned up to avoid reusing stale or closed sockets.</p><p>Set this value lower than the upstream system’s idle timeout.</p><p><strong>Example</strong></p><ul><li>Load balancer closes connections after 60 seconds<br> → configure eviction at 30–50 seconds</li></ul><h4>Connection validation</h4><p>Ensures that connections taken from the pool are still valid.</p><ul><li>Typical range: 2–10 seconds</li><li>Lower values increase safety, with a small performance cost</li></ul><h3>Threads vs Connections</h3><p>Connection pool size should be based on the number of concurrent outbound HTTP calls, not total threads. In a blocking Spring Boot application, each thread making an HTTP request requires a connection, and if none is available, the thread blocks, increasing latency and reducing throughput.</p><p>If threads exceed available connections, requests wait for a free connection, causing higher latency and lower throughput. If connections exceed active threads, many connections remain idle, wasting resources without improving performance.</p><p>The pool should be sized to handle the expected number of simultaneous calls with a buffer for spikes, ensuring threads can access connections efficiently while avoiding resource waste.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=038f14c085ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>