Connection Pools, Timeouts, Retries and Async Work

Connection Pools, Timeouts, Retries and Async Work in Spring Boot: A call centre has a fixed number of phone lines, and one agent can hold one line at a time.

The Analogy: The Call Centre With a Fixed Number of Lines

A call centre has a fixed number of phone lines, and one agent can hold one line at a time. While an agent is on a call that line is unavailable to anyone else, exactly as a database connection is held for the duration of a query. The number of lines is not a comfort setting you raise until complaints stop; it is dictated by how many conversations the building can actually sustain at once, and wiring in more handsets than the exchange supports simply means calls fail in a place no one is watching.

When every line is busy, new callers wait on hold. The hold queue is finite and it is governed by two clocks: a maximum hold time, after which a waiting caller is given a busy signal instead of waiting forever, and a maximum talk time, after which a single rambling call is cut off so it cannot occupy a line all afternoon. Those two limits are the difference between a centre that stays responsive under load and one where a handful of slow calls quietly consume every line.

Callers whose calls drop do not redial in a frenzy. The centre's rule is to wait a little before the first redial, wait longer before the next, and stagger everyone's redial by a random moment so a whole town that lost signal together does not dial back in the same instant. Above all of this sits a supervisor rule: if one destination number has been dead all morning, stop dialling it on every request, send those callers straight to a recorded message for a cooling-off period, and only try a single test call before trusting it again.

The failure mode lives in the overflow voicemail box. Give it no size limit and the floor looks serene: every caller hears "your message has been recorded", no busy signal ever sounds, and no alarm fires. Meanwhile messages arrive faster than agents can return them, the box swells until it exhausts the building's storage, and when the system finally crashes every stored message is lost with no record of who called. A box with a hard capacity that answers "mailbox full, please call back" turns that silent, delayed catastrophe into an honest, immediate signal you can act on.

Syntax or Core Structure

Spring Boot ships HikariCP and sizes the pool from properties. The pool is the set of phone lines: a hard, per-instance ceiling on concurrent database work.

spring:
  datasource:
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5
      connection-timeout: 3000

The pool is per instance, so the load a single database sees is the per-instance pool multiplied by the number of running instances. A bigger pool is usually slower, not faster: each connection is a backend process competing for CPU, memory, and locks, so past the point the database runs work in parallel, extra connections only add contention. Size from the database's ceiling, then check the arithmetic against a database that permits 150 connections:

Output:

instances  pool/inst  requested  db limit  within limit?
--------------------------------------------------------
1          20         20         150       yes
5          20         100        150       yes
8          20         160        150       no
10         20         200        150       no
--------------------------------------------------------
db max connections   : 150
safe instance count  : 7
first over-limit at  : 8

Seven instances stay within the limit; the eighth pushes the total to 160 and every instance begins failing to acquire a connection at once. connection-timeout is what converts that saturation into a fast, visible error instead of threads blocking indefinitely.

Technical Depth: Retries, Backoff and the Breaker State Machine

Retry only what is retryable, with backoff

A retry helps with a momentary blip and harms a sustained outage. The first rule is to retry only responses that might succeed on a second attempt.

ResponseRetryableReason
500 or timeoutyestransient, a later attempt may succeed
400 or 422nodeterministic, a retry repeats the error
401 or 403noauthorisation will not change on retry
409 conflictonly with a keysafe only when an idempotency key dedupes

The second rule is exponential backoff with jitter, so retries spread out in time rather than hammering a struggling dependency in lockstep.

@Retryable(
    retryFor = TransientException.class,
    maxAttempts = 3,
    backoff = @Backoff(delay = 200, multiplier = 2))
public Result call() { ... }

With maxAttempts = 3 there is one initial call and two retries, and the backoff doubles each time. The danger is amplification: the same policy at each hop of a call chain multiplies, so three attempts across three hops is up to twenty-seven calls for one request.

Output:

attempt  backoff before (ms)  cumulative (ms)
---------------------------------------------
1        0                    0
2        200                  200
3        400                  600
---------------------------------------------
max attempts           : 3
retries (attempts-1)   : 2
total backoff (ms)     : 600
3 hops each x3 attempts: 27

The circuit-breaker state machine

A breaker watches the recent failure rate over a sliding window. Closed means traffic flows; when the failure rate crosses the threshold the breaker trips open and calls fail fast through the fallback; after a wait it moves to half-open and admits a few probes that decide whether to close again.

resilience4j:
  circuitbreaker:
    instances:
      payments:
        slidingWindowSize: 4
        failureRateThreshold: 50
        permittedNumberOfCallsInHalfOpenState: 2

Tracing a window of four calls, a 50 percent failure threshold, and two half-open probes makes the transitions concrete:

Output:

call  state before  executed  outcome  window   state after
------------------------------------------------------------
1     closed        yes       ok       0/1      closed
2     closed        yes       fail     1/2      closed
3     closed        yes       fail     2/3      closed
4     closed        yes       fail     3/4      open
5     open          no        short    -        open
6     open          no        short    -        half-open
7     half-open     yes       ok       -        half-open
8     half-open     yes       ok       -        closed
------------------------------------------------------------
window size            : 4
failure threshold      : 50%
trip at call           : 4
calls short-circuited  : 2
half-open probes needed: 2
final state            : closed

Call four fills the window at three failures out of four (75 percent), tripping the breaker open. Calls five and six are short-circuited without touching the dependency; the probes at calls seven and eight both succeed, so the breaker closes and clears its window.

Real World Example: Sizing the Email Executor Under a Burst

An order service sends a receipt email asynchronously so the checkout response does not wait on the mail server. The executor is the call centre: core threads are the always-staffed agents, the queue is the hold line, and the maximum pool is the extra agents pulled in only when the hold line is full.

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean("emailExecutor")
    public Executor emailExecutor() {
        var executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(100);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();
        return executor;
    }
}
@Async("emailExecutor")
public void sendReceipt(Long orderId) { ... }

A ThreadPoolExecutor places work in a strict order: fill the core threads first, then the queue, then create threads up to the maximum, and only then reject. That order is why the queue's bound matters more than any other setting. Submitting a burst of two hundred receipts shows the two regimes side by side:

Output:

config       submitted  core run  queued  extra thr  max run  rejected
-----------------------------------------------------------------------
unbounded    200        4         196     0          4        0
bounded-100  200        4         100     4          8        92
-----------------------------------------------------------------------
core pool size         : 4
max pool size          : 8
bounded queue capacity : 100
unbounded max threads  : 4
bounded max threads    : 8
bounded rejected       : 92

With an unbounded queue the maximum pool size is never reached, because new threads are created only once the queue is full; the pool runs at four forever, the queue swells without limit, nothing is ever rejected, and overload stays invisible until the heap is gone. The bounded queue reaches the full eight threads, holds one hundred, and rejects the remaining ninety-two loudly at the moment of overload, which is the only version an operator can see and act on.

The numbers are deterministic because the placement rule is fixed: nothing here depends on timing, only on the order core, then queue, then max, then reject. That is what makes the two rows reproducible and what makes the unbounded row so treacherous, since its zero rejections read as health right up to the moment the process dies.

The code carries a real design flaw that the arithmetic hides. sendReceipt is a void @Async method, so when AbortPolicy rejects a task the resulting RejectedExecutionException is thrown on a pool thread that nobody observes: the ninety-two rejected receipts simply vanish, and the caller that submitted them has already returned success. Receipts are durable business events sitting on an in-heap queue, where even a clean restart loses everything still queued.

The fix is to treat the executor as a fast path only and persist each receipt to a database table or message broker, so rejection or a restart degrades latency rather than silently destroying records. A second, quieter flaw is that an internal this.sendReceipt() call would bypass the proxy and run synchronously on the request thread, defeating the asynchrony entirely and putting the mail server back in the checkout's critical path.

Common Mistakes

  1. Sizing the pool by request rate instead of database capacity. A pool larger than the database can service adds queueing and lock contention inside the engine, so throughput falls as the pool grows. Size from the database ceiling divided across instances.
  2. Forgetting that the pool is per instance. Twenty connections looks safe until ten instances ask one database for two hundred at once and blow past its connection limit. Multiply before you deploy.
  3. Leaving client calls with no read timeout. A dependency that slows to thirty seconds holds a request thread for thirty seconds; threads pile up, the pool exhausts, and endpoints that never touch that dependency start failing too.
  4. Setting a connect timeout but no read timeout. Establishing the socket quickly is worthless if the response never bounds; both clocks must be set, because a slow response is more dangerous than a refused connection.
  5. Retrying non-idempotent operations blindly. A timeout does not say whether the charge went through, so a blind retry can bill a customer twice. Send a client-supplied idempotency key or do not retry.
  6. Retrying deterministic failures. Retrying a 400 or a 401 only repeats the identical error while multiplying load; retry transient responses only.
  7. Fixed-delay retries with no jitter. Synchronised retries hit a struggling dependency hardest at its worst moment, because every client that failed together dials back in the same instant. Use exponential backoff plus jitter.
  8. A circuit-breaker fallback that throws. A fallback that raises a different exception has achieved nothing; design it to return cached data, a reduced response, or work accepted for later.
  9. An unbounded async queue. An Integer.MAX_VALUE capacity means the maximum pool is never reached and overload is silent until the heap fills and the process dies, losing every queued task.

Best Practices

  • Size the connection pool from the database's connection ceiling divided across all instances, not from your request rate, and recheck the product whenever the instance count changes.
  • Set both a connect timeout and a read timeout on every outbound client, and keep the budget consistent down the chain so a downstream timeout cannot exceed your own.
  • Bound the database side too, with a per-query timeout and a transaction timeout, so one bad statement cannot hold a connection indefinitely.
  • Retry only transient, retryable responses, and only for idempotent operations or ones made idempotent with a client-supplied key.
  • Use exponential backoff with jitter, and account for amplification by capping total attempts across the whole call chain, not just per hop.
  • Put a circuit breaker in front of each remote dependency with a deliberate fallback, and pair it with a bulkhead so one integration cannot consume the whole pool.
  • Give every @Async workload its own named, bounded executor with an explicit rejection policy, so unrelated tasks cannot starve each other.
  • Persist work that must not be lost to a database or broker rather than an in-heap queue, so a restart or a rejection degrades service instead of destroying records.

Practice Exercises

  1. A service runs maximum-pool-size: 25 on each instance against a database that permits 150 connections. Compute the largest instance count that stays within the limit and the first count that exceeds it, and state which instances fail when the limit is crossed.
  2. A @Retryable method uses maxAttempts = 4 with @Backoff(delay = 100, multiplier = 3). Produce the backoff-before-each-attempt schedule and the cumulative delay, then compute the worst-case call count when the same policy sits at each of two hops.
  3. Given a breaker with slidingWindowSize: 4, failureRateThreshold: 50, two half-open probes, and the outcome sequence ok, fail, fail, fail, then two short-circuits, then ok, ok, produce the call-by-call state trace and identify the call at which it trips and the call at which it closes.
  4. An executor has core 4, max 8, and queue capacity 100, and receives a burst of 200 tasks. Compute how many run immediately, how many queue, how many spawn additional threads, and how many are rejected, then explain why the same burst with an unbounded queue rejects none yet is more dangerous.