duo_client_java icon indicating copy to clipboard operation
duo_client_java copied to clipboard

A single OkHttpClient instance should be shared across requests

Open bkoehm opened this issue 10 months ago • 2 comments

com.duosecurity.client.Http is a per-request object and it is instantiating a new OkHttpClient instance in its constructor. OkHttpClient should be shared across all requests rather than a new instance created for each request.

From the OkHttpClient documentation:

OkHttpClients Should Be Shared

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory. Conversely, creating a client for each request wastes resources on idle pools.

bkoehm avatar Feb 07 '25 01:02 bkoehm

@bkoehm I like the idea, but implementation could be tricky. Since we focus on being an API client only, we don't have access to any persistence mechanism to store the OkHttpClient instance. We could introduce our own, but it runs the risk of duplicating/conflicting with any such mechanism that might already exist in the application using the client. Do you have any recommendations on an architecture that could accomplish this without adding a lot of overhead or complexity to the client?

AaronAtDuo avatar Apr 14 '25 18:04 AaronAtDuo

@AaronAtDuo I've mitigated this locally so this is not a major issue for me any longer. But, to keep it simple, I would suggest adding a constructor with a OkHttpClient httpClient parameter and/or adding a setter for the httpClient field. A user, if they so choose, could then hold themselves responsible for managing the OkHttpClient instance.

bkoehm avatar Apr 14 '25 18:04 bkoehm