Product knowledge · Advanced · Service-owned outbound

Outbound HTTP starts with a declared dependency, not an arbitrary URL.

Application selects the logical dependency and business policy. CoAkka HTTP Runtime owns the bounded target registry, endpoint/DNS/pool/TLS mechanics, request progress and typed terminal outcome.

01 · Ownership model

A service calls a dependency through its own contract

Application

Names dependencies; owns authorization/credential intent, request meaning, status mapping, idempotency and retry policy.

CoAkka HTTP Runtime

Validates target snapshots; owns endpoint selection, DNS, pools, TLS, redirects, HTTP framing, deadlines and terminal facts.

Connector

Projects natural builders, requests and terminals while protecting type, buffer, callback and owner lifetime.

Remote service

Owns its HTTP response and business effect. A received response is not automatically business success.

Do not call this surface CoAkka HTTP Client. These are outbound APIs of a CoAkka HTTP Runtime service; CoAkka HTTP Client is a separate planned product.

02 · Logical target declaration

Freeze allowed destinations before accepting traffic

logical target: sample.upstream · generation 1
  endpoint: loopback
  connect: 127.0.0.1:<port>
  HTTP authority: 127.0.0.1:<port>
  security: plaintext for this local example

incoming request data ──X──► arbitrary scheme/host/port

Logical targets are construction-time snapshots. A handler selects a declared dependency name; it never turns caller query, headers or body into an arbitrary outbound destination.

03 · Target fields

Address, authority and identity answer different questions

Name
Stable application key such as sample.upstream; requests use it instead of an arbitrary URL.
Generation
Identity/version of the target snapshot reflected in terminals; not a timestamp or retry permission.
Strategy
SINGLE_OWNER selects one eligible owner; WEIGHTED_ROUND_ROBIN distributes using relative endpoint weights when multiple candidates exist.
Endpoint + node ID
Allowed candidate and stable attribution for the selected endpoint; the list stays finite.
Weight / available
Weight is relative selection input, not percentage or connection limit. Available controls candidate eligibility in the snapshot; it is not a health proof.
Connect host / port
Network address used for DNS/connect. It is not automatically HTTP authority or TLS peer identity.
HTTP authority
Request authority/Host for the target contract; separate from the socket address.
Security + TLS peer identity
Plaintext, TLS or mTLS intent and certificate identity to verify; the exact package must accept the provider.
Trust / client identity generation
Selects the declared immutable CA set and optional mTLS certificate/key set; generation is identity, not secret or file watcher.

04 · Request intent

Path is a concrete origin-form value, not a route template

submit:
  logical target = sample.upstream
  method         = GET
  path/query     = /orders/A%2FB?view=summary
  headers/body   = bounded application values
  call deadline  = 3000 ms

returns: call identity · not an HTTP response

Resolve variables and URL-encode values before submit. Never put /orders/{id}, an arbitrary full URL or raw untrusted text in the path/query field.

05 · Request fields

Every field has a specific budget and owner

FieldMeaning
Logical targetSelects a declared dependency snapshot, not an arbitrary socket.
MethodHTTP method of the call; it does not prove the operation is safe or idempotent to retry.
Path/queryConcrete encoded origin-form request target; no fragment or route syntax.
Headers/bodyOrdered bounded HTTP values; application owns auth token, media type, codec and secret policy.
Call deadlineFinite monotonic operation budget; distinct from reader wait and inbound handler/transport timeouts.
Call identityOpaque slot/generation returned after accepted admission; use it to match the exact terminal.

06 · Call lifecycle

Successful submit means admission, not response

1

Declare + start

Builder supplies a finite target snapshot; Core validates capability, targets and bounds before readiness.

2

Submit

Core admits or refuses the request and returns a call identity. No remote response exists yet.

3

Progress

Core selects an endpoint, resolves/connects, applies security, sends the request and reads a bounded response under deadline.

4

Terminal

One typed terminal tied to call identity reports cause, phase and certainty plus an optional HTTP response.

07 · Terminal facts

Match identity first; status matters only for a response terminal

Call identity
Must match the submitted call; JavaScript keeps exact integer identity rather than rounding through Number.
Target / generation / selected endpoint
Runtime attribution for the declared snapshot and actual selected endpoint.
Reason
Stable terminal cause; branch on enum/code, never text.
Phase
One of ADMISSION, PROVIDER_ADOPTION, TRANSPORT, RESPONSE, CANCELLATION, SHUTDOWN.
Retry disposition
Runtime transport fact; it never authorizes replaying business work or skipping idempotency.
Certainty
What the runtime knows about request/response bytes; ambiguity never proves the remote business effect did not happen.
Optional response
Status, headers and bounded body only when reason confirms a response. HTTP 404/500 can still be RESPONSE.

Preserve unknown numeric enum values for forward compatibility; never coerce one into a known category.

08 · Exact terminal vocabulary

Read runtime facts before choosing an application action

DimensionStable values and meaning
ReasonRESPONSE; PROVIDER_FAILURE/PROVIDER_REJECTED/INVALID_PROVIDER_RESULT; CANCELLED/DEADLINE_EXCEEDED/STOPPED; RESPONSE_HEAD_LIMIT/RESPONSE_BODY_LIMIT/RESPONSE_AGGREGATE_LIMIT; OUT_OF_MEMORY; CLOCK_FAILURE.
RetryNEVER, IF_SAFE, DELIVERY_UNCERTAIN. This is transport disposition; IF_SAFE still requires application proof of safe/idempotent behavior.
CertaintyNO_REQUEST_BYTES_SENT, REQUEST_UNCERTAIN, RESPONSE_HEAD_OBSERVED, COMPLETE_RESPONSE. These describe wire evidence, not business commit state.
Provider code / diagnosticBounded operator evidence; never branch business logic on diagnostic text or copy it into a public response.

09 · Capacity and time

Pools, redirects and terminal queues are never unlimited

BoundaryRequired law
Target registry / endpointsFinite declared entries; invalid or unsupported targets fail closed.
DNS / connections / poolsFinite work, connections and retained idle state; exact target owns capability/effective facts.
In-flight callsFinite ceiling; pressure/refusal never becomes a hidden application queue.
RedirectsFinite hop/policy bound; authority, credential scope and TLS identity remain valid.
ResponseFinite header/body/retained-terminal bytes; application never collects past the ceiling.
Call deadlineOperation progress budget. A deadline terminal differs from reader wait timeout.
Terminal reader waitWindow for retrieving an event; expiry only means no terminal was observed in that window.

10 · DNS, TLS and redirects

Where to connect, whom HTTP addresses and whom TLS verifies are distinct

Connect address

DNS/IP/port used to open the connection; it can differ from HTTP authority.

HTTP authority

Logical Host/authority and virtual hosting; never infer it from a resolved IP.

TLS peer identity

Certificate identity verified with trust roots; an mTLS client identity is separate material.

Redirect

Every hop remains bounded and follows configured trust/credential policy; never forward a secret by guesswork.

Feature-check outbound and security providers on the exact package. Never put private keys, tokens, raw credentials or operator-only TLS diagnostics in a public response.

Advanced · Outbound HTTP

Call a local upstream and distinguish HTTP 404 from a failed call

Run a local upstream first. Each CoAkka caller declares upstream with a fixed address and authority, submits one GET, then reads the matching result. The example never takes an arbitrary URL from the incoming request.

Terminal · upstream · Python 3.11+
mkdir -p upstream-lab
printf 'hello upstream\n' > upstream-lab/hello.txt
python3 -m http.server --protocol HTTP/1.1 8091 --bind 127.0.0.1 --directory upstream-lab
C/C++ · SDK 2.3.0

Use the verified SDK 2.3.0. Save outbound.c in a second terminal’s project folder. The same C ABI source builds with either compiler on Linux and macOS.

outbound.c
#include <coakka/http/host.h>

#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static coakka_http_host_bytes_t bytes(const char *text) {
  coakka_http_host_bytes_t span;
  span.data = (const uint8_t *)text;
  span.size = strlen(text);
  return span;
}

static bool check(coakka_http_host_status_t status, const char *operation) {
  if (status == COAKKA_HTTP_HOST_OK) {
    return true;
  }
  fprintf(stderr, "%s: %s\n", operation, coakka_http_host_status_name(status));
  return false;
}

static bool request_once(coakka_http_host_service_t *service) {
  coakka_http_host_outbound_request_t request;
  coakka_http_host_outbound_request_init(&request);
  request.logical_target = bytes("upstream");
  request.method = bytes("GET");
  request.target = bytes("/hello.txt");
  request.timeout_ms = 3000U;

  coakka_http_host_outbound_call_t call;
  if (!check(coakka_http_host_submit_outbound(service, &request, &call),
             "submit outbound request")) {
    return false;
  }

  coakka_http_host_outbound_event_t event;
  coakka_http_host_outbound_event_init(&event);
  if (!check(coakka_http_host_take_outbound(service, 5000U, &event),
             "take outbound result")) {
    return false;
  }
  const bool matched =
      event.call.slot == call.slot && event.call.generation == call.generation;
  const bool replied =
      matched && event.reason == COAKKA_HTTP_HOST_OUTBOUND_RESPONSE;
  if (replied) {
    printf("HTTP %u\n", (unsigned)event.response_status);
    if (event.response_status == 200U && event.response_body.size != 0U) {
      // The response body is borrowed until the result is released.
      fwrite(event.response_body.data, 1U, event.response_body.size, stdout);
    }
  } else {
    fprintf(stderr,
            "Outbound result: matched=%d reason=%" PRIu32 " phase=%" PRIu32
            "\n",
            (int)matched, event.reason, event.phase);
  }
  const bool released =
      check(coakka_http_host_release_outbound(service, &event),
            "release outbound result");
  return replied && released;
}

int main(void) {
  coakka_http_host_outbound_endpoint_t endpoint;
  coakka_http_host_outbound_endpoint_init(&endpoint);
  endpoint.node_id = bytes("local");
  endpoint.connect_host = bytes("127.0.0.1");
  endpoint.connect_port = 8091U;
  endpoint.http_authority = bytes("127.0.0.1:8091");
  endpoint.available = 1U;

  coakka_http_host_outbound_target_t target;
  coakka_http_host_outbound_target_init(&target);
  target.name = bytes("upstream");
  target.generation = 1U;
  target.endpoints = &endpoint;
  target.endpoint_count = 1U;

  coakka_http_host_configuration_t configuration;
  coakka_http_host_configuration_init(&configuration);
  configuration.bind_address = bytes("127.0.0.1");
  configuration.outbound_targets = &target;
  configuration.outbound_target_count = 1U;

  coakka_http_host_service_t *service = NULL;
  uint32_t failed_route = COAKKA_HTTP_HOST_FAILED_INDEX_NONE;
  if (!check(coakka_http_host_service_create(&configuration, NULL, 0U, &service,
                                             &failed_route),
             "create outbound service")) {
    return EXIT_FAILURE;
  }
  coakka_http_host_issue_t issue;
  coakka_http_host_issue_init(&issue);
  const bool replied =
      check(coakka_http_host_service_start(service, &issue), "start service") &&
      request_once(service);
  const bool closed =
      check(coakka_http_host_service_destroy(&service), "destroy service");
  return replied && closed ? EXIT_SUCCESS : EXIT_FAILURE;
}
C11
cc -std=c11 -I"$COAKKA_HTTP_SDK/include" outbound.c -L"$COAKKA_HTTP_SDK/lib" \
  -Wl,-rpath,"$COAKKA_HTTP_SDK/lib" -lcoakka_http_host -o outbound-c
./outbound-c
C++20
c++ -x c++ -std=c++20 -I"$COAKKA_HTTP_SDK/include" outbound.c -L"$COAKKA_HTTP_SDK/lib" \
  -Wl,-rpath,"$COAKKA_HTTP_SDK/lib" -lcoakka_http_host -o outbound-cpp
./outbound-cpp
Kotlin/JVM

Use the 2.3.2 JVM project. Save the file under src/main/kotlin or src/main/java, in the study/ directory. The commands default to macOS ARM64. On Pi, add -Dcoakka.target=linux-aarch64 to Maven or -PcoakkaTarget=linux-aarch64 to Gradle.

KotlinOutbound.kt
package study

import coakka.http.OutboundEndpoint
import coakka.http.OutboundReason
import coakka.http.OutboundRequest
import coakka.http.OutboundStrategy
import coakka.http.OutboundTarget
import coakka.http.ServiceBuilder

fun main() {
    val endpoint = OutboundEndpoint(
        nodeId = "local",
        connectHost = "127.0.0.1",
        connectPort = 8091,
        httpAuthority = "127.0.0.1:8091",
    )
    val target = OutboundTarget(
        name = "upstream",
        generation = 1,
        strategy = OutboundStrategy.SINGLE_OWNER,
        endpoints = listOf(endpoint),
    )
    ServiceBuilder().listen("127.0.0.1", 0).outboundTarget(target).start().use { service ->
        val call = service.submitOutbound(OutboundRequest(
            logicalTarget = "upstream",
            method = "GET",
            target = "/hello.txt",
            timeoutMillis = 3_000,
        ))
        val result = checkNotNull(service.takeOutbound(5_000)) { "Missing outbound result" }
        check(result.call == call) { "Result belongs to a different call" }
        check(result.reason == OutboundReason.RESPONSE) { "Outbound request ended: ${result.reason}" }
        println("HTTP ${result.responseStatus}")
        if (result.responseStatus == 200) print(result.responseBody().toString(Charsets.UTF_8))
    }
}
Maven
mvn -q compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.KotlinOutboundKt
Gradle
./gradlew runKotlinOutbound
Java/JVM

Use the 2.3.2 JVM project. Save the file under src/main/kotlin or src/main/java, in the study/ directory. The commands default to macOS ARM64. On Pi, add -Dcoakka.target=linux-aarch64 to Maven or -PcoakkaTarget=linux-aarch64 to Gradle.

JavaOutbound.java
package study;

import coakka.http.Headers;
import coakka.http.OutboundCallId;
import coakka.http.OutboundEndpoint;
import coakka.http.OutboundReason;
import coakka.http.OutboundRequest;
import coakka.http.OutboundStrategy;
import coakka.http.OutboundTarget;
import coakka.http.OutboundTerminal;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;

public final class JavaOutbound {
    private JavaOutbound() {}

    public static void main(String[] args) throws Exception {
        OutboundEndpoint endpoint = new OutboundEndpoint(
                "local", "127.0.0.1", 8091, "127.0.0.1:8091");
        OutboundTarget target = new OutboundTarget(
                "upstream", 1L, OutboundStrategy.SINGLE_OWNER, Collections.singletonList(endpoint));
        Service service = new ServiceBuilder()
                .listen("127.0.0.1", 0)
                .outboundTarget(target)
                .start();
        try {
            OutboundCallId call = service.submitOutbound(new OutboundRequest(
                    "upstream", "GET", "/hello.txt", new Headers(), new byte[0], 3_000));
            OutboundTerminal result = service.takeOutbound(5_000L);
            if (result == null || !result.getCall().equals(call)) {
                throw new IllegalStateException("Missing result for this call");
            }
            if (result.getReason() != OutboundReason.RESPONSE) {
                throw new IllegalStateException("Outbound request ended: " + result.getReason());
            }
            System.out.println("HTTP " + result.getResponseStatus());
            if (result.getResponseStatus() == 200) {
                System.out.print(new String(result.responseBody(), StandardCharsets.UTF_8));
            }
        } finally {
            service.close();
        }
    }
}
Maven
mvn -q compile dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
  -cp "target/classes:$(cat target/classpath.txt)" study.JavaOutbound
Gradle
./gradlew runJavaOutbound

For other languages, open the complete outbound exercise: Go · Python · Node.js · Bun · C# · Swift.

With the file present, expect HTTP 200 and hello upstream. Rename hello.txt and repeat: HTTP 404 is still a response, not a transport failure. Stop the upstream and repeat to see a non-response outcome. A read deadline is not permission to replay an application operation.

11 · Cancellation, retry and idempotency

A terminal fact is decision input, not a retry command

Cancel

Cancellation is intent until the matching terminal confirms outcome. Do not free caller state while Core still owns the call.

Deadline

Expiry does not prove the remote missed the request or effect; the response may have been lost on return.

Application retry

Create a new attempt/call identity with bounded attempts, backoff and total budget; retain a business idempotency key when required.

Reconcile

For charge/create/non-idempotent work with ambiguous outcome, read authoritative business state before repeating.

12 · Failure law

Do not turn every result into an exception or status

Observed outcomeMeaning / next action
Startup target refusalDeclaration, capability or bound is invalid; the candidate service is not ready.
Synchronous submit refusalCall was not admitted; inspect stable category and pressure/closed state.
Transport/provider terminalNo HTTP response; branch on reason/phase/retry/certainty and repair the network/security/provider owner.
HTTP 4xx/5xx responseRemote returned an HTTP response; application decides business mapping and retry.
Cancel/deadline terminalPreserve ambiguity; never infer rollback or exactly-once.
Reader wait timeoutNo terminal arrived during the wait window; never submit a duplicate automatically.
Close/drain refusalRetain service, call and application owners until cleanup converges.

13 · Integration checklist

Before choosing a language API