Skip to content

HTTP client

The HTTP client calls other services. In Java it is a blocking client built for virtual threads on Vert.x (framework-httpclient, with framework-httpclient-module as the framework adapter). In Go it is package httpclient on net/http, with httpclient/module as the adapter. Both libraries import nothing else of the framework, so they work outside it. The normative text is the HTTP client specification.

One service client exists per service you call, each with its base URL, timeouts, retry policy and authentication. Behaviour is the same in both languages unless a section says otherwise.

Each client is named in code with how it behaves. Configuration gives only its base URL and the credentials of its authentication strategy: an application can have many clients with different policies, so policy is code (see config and code).

HttpClientModule module =
HttpClientModule.builder()
.client("platform", HttpClientOptions.defaults().withAuth(ClientAuth.clientCredentials().withScope("api")))
.build();
http-clients:
instances:
platform:
base-url: https://platform.example.com
auth:
token-url: https://platform.example.com/oauth/token
client-id: orders-service
# client-secret: from the environment, HTTP_CLIENTS_INSTANCES_PLATFORM_AUTH_CLIENT_SECRET

Then, in a handler or use case, with the Context you are working in:

ServiceClient billing = app.get(ServiceClients.class).get("billing", ctx);
billing.get("/invoices/{id}").pathParam("id", "i1").send().status();

get(name, ctx) sends X-Correlation-Id with the context’s correlation id on every request, and nothing else from the context (the client id is not sent to other services).

HttpClientOptions is checked when built (IllegalArgumentException):

Method Default Meaning
withConnectTimeout(Duration) 5s More than 0, at most 1 h
withRequestTimeout(Duration) 30s Per attempt, the whole exchange including the body. More than 0, at most 1 h
withMaxResponseBytes(long) 10485760 1 B to 1 GiB. Larger answers fail (RESPONSE_TOO_LARGE)
withRetry(RetryPolicy) 3 attempts, 200ms to 5s, Retry-After up to 30s See Retries
withAuth(ClientAuth) ClientAuth.none() The strategy. Its credentials come from configuration

.client(name, config -> ...) computes the options from a setting of your own. new HttpClientModule() is the engine defaults with no named client.

Configuration of a client <n> lives under http-clients.instances.<n>: base-url (required; an absolute http(s) URL whose path is a prefix of every request) and the credentials its authentication strategy reads, all required.

Strategy Keys under auth
none none
bearer token (secret)
basic username, password (secret)
header (name is code) value (secret)
client credentials (with scope, audience, method POST or BASIC) token-url, client-id, client-secret (secret)

Give secrets through the environment or a local secrets file. A key the strategy does not read, a section with no client of that name in code, and a client named in code without a base-url all fail start-up, and all such problems are reported at once. The engine that every client shares is configuration:

Key Default Notes
http-client.max-connections-per-host 50 (1 to 1000) Env HTTP_CLIENT_MAX_CONNECTIONS_PER_HOST
http-client.event-loops 2 (1 to 64) Java only. Go has no event-loop pool, so the key is not declared and giving it fails start-up

The old per-client keys (driver, connect-timeout, retry.*, auth.type) are removed in Go and fail start-up.

A client authenticated with something only known at run time (for example the platform’s own token) is added with register:

ServiceClient api =
app.get(ServiceClients.class)
.register(
ServiceOptions.builder("platform", app.config().get(FlowCatalystModule.BASE_URL))
.auth(Auth.bearer(platformClient::accessToken, platformClient::clearToken))
.build());

In Java a name is unique and a client lives until it is removed. A client per route version, tenant or ingestion must be removed when it is done, or its metrics series pile up. Use a scoped registration, unregister or replace:

try (ServiceClients.Registration r = clients.registerScoped(options)) {
r.client().get("/ping").send();
}
clients.unregister("route-v1"); // true when it was registered here
clients.replace(options); // register, or swap the registered client of that name

Removing a client removes its service series from the two metrics below. It is safe while the client is in use: calls in flight finish, and a reference still held keeps working but is no longer measured. Configured clients (from the module builder) cannot be removed or replaced. In a unit test with no App, build the registry directly with ServiceClients.create(HttpClients.create(), Metrics.memory(1000, MonotonicClock.system())).

Order order =
client()
.get("/orders/{id}")
.pathParam("id", "a/b c?#")
.query("q", "x&y=z")
.sendJson(Order.class);

get, post, put, patch, delete, head and request(method, path) start a request. Then pathParam, query, header, json(value), body(bytes, contentType), form(map), idempotencyKey(key), retryable(boolean) and timeout(duration).

  • send() returns a ClientResponse whatever the status: status(), isSuccess(), header(name), bodyText(), bodyBytes(), json(Class) and json(TypeReference).
  • sendJson(type) decodes a 2xx body and throws UnexpectedStatusException otherwise, with the status and, when the answer is the platform’s error envelope, its error code. It never includes the body.
  • getJson(path, type, pathParams...) and postJson(path, body, type) are shorthands.
  • JSON is the framework’s Jackson 3, tolerant of unknown properties when reading, because other services add fields.

A request can never leave its service. The path must start with / and may not contain //, ?, #, \, or . and .. segments. A path parameter is percent-encoded as one segment (so /, ? and # cannot sneak in) and may not be empty, . or ... Header values with CR, LF or NUL are refused (no header injection), and Host, Content-Length, Transfer-Encoding and Connection are set by the client only. In Java these are IllegalArgumentExceptions before anything is sent; in Go they are collected and returned by Send as an error wrapping ErrInvalidRequest, also before anything is sent.

Redirects are not followed, because they would carry your Authorization header elsewhere. A 3xx is returned as the response.

A call with no response fails with a kind:

Kind Meaning
CONNECT, TIMEOUT, IO Transport failures (retried)
RESPONSE_TOO_LARGE The answer exceeded MaxResponseBytes
DECODE The body is not the JSON asked for
AUTH No credentials, for example a failing token endpoint
INTERRUPTED (Java) / CANCELED (Go) The thread was interrupted, or the context was cancelled or expired. Never retried
UNEXPECTED_STATUS (Go) A non-2xx answer to ReceiveJSON

Messages name the service, method and path template, never header values, bodies, tokens or query strings. In Go, errors are values (*Error with a Kind); in Java they are HttpClientException with a kind(). Go also decodes gzip and deflate answers and holds the decoded body to the same size limit, so a small compressed body cannot expand without bound.

Only requests that are safe to repeat are retried: GET, HEAD, OPTIONS, PUT, DELETE, a request with an idempotency key (sent as Idempotency-Key), or one marked retryable(true). POST and PATCH are never retried otherwise. retryable(false) sends any request once.

Retried: connect, timeout and I/O failures, and the statuses 429, 502, 503 and 504. Waits double from the policy’s initial backoff to its maximum with jitter. A Retry-After up to the policy’s maxRetryAfter is honoured; a longer one returns the response at once instead of blocking. When attempts run out, the last response is returned.

Strategy Sends
none nothing
bearer (supplier) Authorization: Bearer ..., asked per attempt
bearer with an unauthorised callback as above; after a 401 the callback runs and the request is sent once more
basic Authorization: Basic ...
API-key header a header of your choosing
client credentials OAuth 2 client credentials

Client credentials fetch a token once and reuse it until shortly before it expires (expires_in minus up to 30 seconds; in Go minus min(30s, expires_in/10), or five minutes when the response has no expires_in). Concurrent callers share one token request. After a 401 the token is dropped and the request is sent once more with a new one, whatever the method (a 401 means the request was not processed); a second 401 is returned. The client id and secret go in the form body by default (method BASIC puts them in an Authorization header). The token URL must be https, or http to localhost. A failing token endpoint’s message carries the host and the status, never the secret or the answer.

Every attempt is counted in fw_http_client_requests_total{service, method, outcome} (the status, or the failure kind in lower case) and timed in fw_http_client_request_duration_seconds{service, method}. See background work and metrics. Without the framework module in Java, pass a ClientObserver to ServiceOptions.builder(...).observer(...).

To see what a piece of work’s outbound calls sent and received (a trace or a diagnostic), bind a sink around it. Every attempt a ServiceClient makes while it is bound, a retry included, is handed to the sink as an HttpCapture.Exchange:

ScopedValue.where(HttpCapture.CURRENT, exchange -> record(exchange))
.run(() -> client.get("/x").send());

An Exchange holds the service name, method, the full URL with its query, the request headers and body, the status, the response headers and body, the attempt (1 for the first) and the duration. A transport failure has status 0 and the failure kind. Header values of a sensitive name (containing, in any case, auth, key, token, secret, password, signature, cookie or session) are already [redacted]; HttpCapture.redactHeaders(map) applies the same rule to other headers. Bodies are not redacted: they are yours to filter. The sink runs on the calling thread after the attempt, so keep it quick. Anything it throws is logged and ignored, so capturing never changes a request, its retries or its response. There is no capture hook in the Go client.

try (HttpClients clients = HttpClients.create()) {
ServiceClient orders =
clients.service(ServiceOptions.builder("orders", URI.create("https://orders.example.com")).build());
}

HttpClients owns the engine (Vert.x and its connection pools). Create one and close it at the end; using a client after that is IllegalStateException.

The framework’s own tests run the client against a fake server on a free local port. TLS is not covered by a test: https uses the platform’s TLS with host verification and the default trust store.