Search code examples
spring-bootstaticmicroserviceswebclientspring-webclient

Why web-clients in micro-services architecture are static?


In one of my recent interviews, I was asked this question -"Why micro-service's clients are always static/singleton? What will happen if we make them non-static?"

Based on my understanding of "Static" and "singleton" in java, I tried to articulate my thoughts around this question but failed.

I did my fundamental checks like Google search, discussion with peers but could not get any precise/direct answer. The interview is done, I got the offer as well but that question is still stuck in my head and I really want to know the answer.

I would really appreciate it if anyone can help me answer this question so I can rest :)


Solution

  • External service clients are often defined as static or singleton instances for performance reasons:

    1. Resource Efficiency: Creating a new client instance for every request can lead to excessive memory consumption and slow down the application due to repeated initialization and resource allocation.

    2. Connection Management: Many clients establish and manage connections to remote services. Keeping a single instance alive allows the client to maintain connections and reuse them across multiple requests, reducing the overhead of establishing a new connection for each operation.

    Therefore, reusing a single instance enhances performance through connection pooling and reduced object initialization overhead.