Product knowledge · Advanced · Operations

Bound everything retained; shutdown finishes only when the owner can actually be released.

CoAkka HTTP Runtime uses finite admission, queues, retained bytes and monotonic deadlines. Pressure/refusal is control flow; a drain/stop timeout never permits success plus freeing still-live state.

01 · Resource map

Capacity is not one max_requests knob

BoundaryFinite shape to account forOwner
Routes + live controlRoute/segment/capture/metadata bytes, activation receipts, control queue/history and commands per turn.Core reservation; App Host retains bounded prepared/draining handlers.
Listener + admissionConnections, active requests, request/completion queues, completion batch and terminal queue.CoAkka HTTP Runtime.
Request + responseHeader count/bytes, target/body bytes, retained values and completion lifetime.Core at wire/admission; connector/application for copied values.
Request/response streamsChunk slots/bytes, retained items/per-stream/total bytes, trailers and write/progress deadline.Core slots; application producer/consumer queues.
Files + compressionMount/assets/authorities, active reads, response bytes and compression eligibility/output/workspace.Core delivery; application authorization; deployment bytes.
SSE + WebSocketSessions, frame/event/message bytes, pending output, source backlog and reconnect/drain window.Core protocol; application event/session policy.
Outbound HTTPTarget/endpoint/trust/identity sets, DNS/pools, in-flight calls, redirects, responses and terminals.Core transport; application business retry/idempotency.
Monitor + inspectionEvent ring/page, failure rows, latency buckets, inspection response/cache and exporter queue.Core reservation; application exporter; deployment exposure.
Application dependenciesExecutors/tasks/goroutines, database pools, caches, retries, handler state and shutdown hooks.Application/App Host; never a hidden Core queue.

02 · Requested versus effective

Zero can select a bounded default; only Core knows the accepted state

1

Declare intent

The builder/host supplies required capabilities, limits and optional startup reservations.

2

Plan capability shape

The service plan compares requirements with adapter facts. It does not probe the OS, choose a second data plane or prove a matching-host package.

3

Construct + validate

Core resolves zero/dependent defaults once, validates relationships/capacity and fails closed for an invalid candidate.

4

Read effective limits

Read the complete accepted startup limits from the service; never echo input or mirror a default table in a connector.

Startup limits are not hot-reloadable. To change reservations, create a replacement service, verify readiness/handshake, shift ingress, then drain the old instance.

03 · SDK 2.3.0 limits

Group fields by the state they protect

GroupRepresentative effective fields
Route/controlmax_routes, total segments/route bytes/metadata, captures, activation history, route-control capacity/history/commands per turn.
Admission/terminalmax_connections, max_active_requests, request/completion/terminal queue capacity and completion batch.
HTTP valuesHeader count/bytes and request/response body bytes.
Stream retentionRequest/response chunk slots, max chunk/trailer bytes, retained items and per-stream/total retained bytes.
SchedulingDeadline tick, connection-timeout batch and request/terminal notification profiles. Event-loop CPU mask is placement intent, not process CPU quota/thread count.
Progress deadlinesKeep-alive, header, body, handler, idle, response-write, drain and stop timeouts.

Other bounds such as static mounts, outbound declarations, compression and Monitor live in separate configuration but remain a finite construction-time shape. Absence from limits never implies unbounded.

04 · Failure vocabulary

Full, too large, out of time and cancelled require different action

OutcomeMeaningNext action
Pressure / capacity exhaustedA finite slot/queue is full now.Back off, shed/refuse or tune from evidence; never create a hidden queue.
LimitAn item/byte count exceeds an accepted ceiling.Change the input/contract or replacement reservation; identical retry cannot help.
TimeoutThe correct phase's progress deadline expired.Preserve phase/certainty; never infer business effect or cleanup rollback.
CancellationPeer/application/lifecycle requested owned work to stop.Stop producer/downstream work, wait for the matching terminal, then clean up.
ClosedThe surface no longer admits this operation in its lifecycle.Do not resubmit to a stopped owner; finish release/rollout at the correct scope.
UnsupportedThe exact package/adapter/target does not expose the capability.Feature-check and choose a supported path; never silently fall back.
Application/service failureHandler/dependency failed or the service owner became terminal.Preserve owner, structured cause and distinct mapping; never collapse to generic 500.

Refused work is not admitted into an unlimited wait. Accepted work reaches completion, failure, timeout, cancellation, disconnect or service stop and the same cleanup owner.

05 · Backpressure law

Pause, shed or cancel—never busy-loop or multiply backlog

Inbound

Listener/admission decides before the handler; a body limit does not collect more and refuse later.

Handler dispatch

If a connector has a queue, bound both items and retained bytes. Otherwise active-handler/event-loop admission is the bound.

Streaming/realtime

Producers write only when writable, use a finite progress deadline and stop on cancel/disconnect/drain.

Application dependencies

DB pools, task queues, caches, retries and exporters have their own pressure policy; Core never absorbs overload for the application.

06 · Time scopes

One timeout does not replace every other deadline

Keep-alive / header / body / idle
Protocol/connection progress scopes; separate from the handler business deadline.
Handler timeout
Budget for an accepted application exchange under contract; it does not automatically cancel every downstream system.
Response-write timeout
Transport progress while output is stalled; distinct from total response generation time.
Outbound call deadline
Remote HTTP operation; reader wait is only terminal retrieval and grants no duplicate retry.
Drain timeout
Core native drain budget. Wait expiry or expired drain never proves business rollback.
Stop timeout
Finite Core stop/join budget; it does not cover arbitrary application cleanup.
Outer process budget
Deployment/App Host covers ingress withdrawal, application cleanup and escalation; a forced kill can bypass hooks.

Use monotonic time for progress budgets. Wall-clock changes must not make a request/drain live forever or expire early.

07 · Ordered shutdown

One owner coordinates; accepted work still needs a progress path

1

Receive explicit intent

The App Host opts into a process signal/shutdown hook; deployment withdraws the instance from ingress first when rollout requires it.

2

Begin drain

Core closes new admission by lifecycle. Never stop the request reader/handler before accepted work can progress.

3

Wait boundedly

Observe the aggregate native drain barrier within a finite window while handlers, streams and readers keep running.

4

Converge application work

Stop app producers/downstream/retry, interrupt and join owned waiters by connector contract; Monitor has explicit interrupt.

5

Stop Core

Stop the protocol/transport owner and completion admission; inspect the typed result. Stop does not free the service.

6

Retire observations + leases

Consume or intentionally abandon queued results by contract; release every successful borrowed request/WebSocket/outbound event lease.

7

Destroy the owner

Serialize destruction. Only completed destroy nulls/frees; refusal preserves the service pointer for cleanup and retry.

08 · Drain observation

Wait ending and drain ending are different facts

Core stateMeaning
NOT_STARTEDDrain has not begun; waiting is invalid usage and never starts it implicitly.
PENDINGThe caller's wait window ended but the native barrier has not converged; not a transport timeout or stop.
COMPLETENative work quiesced. It does not prove every exchange succeeded, the peer consumed bytes or queued/borrowed results were released.
EXPIREDUnfinished native work was forced at the Core drain deadline; preserve failure/terminal evidence.
ABORTEDDrain was closed/aborted by lifecycle; this is not graceful success.
FAILEDThe barrier produced no complete fact; retain the owner and structured evidence.
UNSUPPORTEDThe exact scope/package lacks support; never fabricate complete.

In SDK 2.3.0, wait accepts 0..60000 ms; zero inspects once. It does not stop Core, consume an event, release a caller lease or reopen admission.

Run the drain lab with a request in flight

Study · Go

Drain a service with a request in flight

The Go lab runs one service on loopback. It holds GET /held in its handler and calls Service.Close() outside that handler. After Core closes admission, the lab sends GET /new on a fresh connection and then lets the original handler respond.

Set up Go and SDK 2.3.0 using the Go installation lesson. In an empty directory, save the source as drain.go and replace the SDK path below.

Go source · drain.go
drain.go
package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"sync"
	"sync/atomic"
	"syscall"
	"time"

	coakkahttp "github.com/phuong-tran/coakka-http-runtime-go/v2"
)

const heldBody = "held request finished\n"

type reply struct {
	status int
	body   string
	err    error
}

func get(ctx context.Context, client *http.Client, url string) reply {
	request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return reply{err: err}
	}
	response, err := client.Do(request)
	if err != nil {
		return reply{err: err}
	}
	defer response.Body.Close()
	body, err := io.ReadAll(io.LimitReader(response.Body, 256))
	return reply{status: response.StatusCode, body: string(body), err: err}
}

func waitForAdmissionToClose(ctx context.Context, service *coakkahttp.Service) (coakkahttp.Health, error) {
	ticker := time.NewTicker(10 * time.Millisecond)
	defer ticker.Stop()
	for {
		health, err := service.Health()
		if err != nil || !health.AdmissionOpen {
			return health, err
		}
		select {
		case <-ctx.Done():
			return coakkahttp.Health{}, ctx.Err()
		case <-ticker.C:
		}
	}
}

func run() (err error) {
	ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
	defer cancel()

	entered, release := make(chan struct{}), make(chan struct{})
	markEntered := sync.OnceFunc(func() { close(entered) })
	releaseHandler := sync.OnceFunc(func() { close(release) })
	var newHandlerCalls atomic.Int32

	service, err := coakkahttp.NewBuilder().
		Listen("127.0.0.1", 0).
		Limits(coakkahttp.Limits{ShutdownTimeoutMillis: 5000}).
		Get("/held", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			markEntered()
			select {
			case <-release:
				return coakkahttp.Text(http.StatusOK, heldBody)
			case <-ctx.Done():
				return coakkahttp.Text(http.StatusGatewayTimeout, "lab deadline\n")
			}
		}).
		Get("/new", func(*coakkahttp.Request) (coakkahttp.Response, error) {
			newHandlerCalls.Add(1)
			return coakkahttp.Text(http.StatusOK, "new request reached its handler\n")
		}).
		Start()
	if err != nil {
		return err
	}

	closed := make(chan error, 1)
	// Close waits for handlers, so the driver calls it outside the handler.
	startClose := sync.OnceFunc(func() {
		go func() { closed <- service.Close() }()
	})
	defer func() {
		releaseHandler()
		startClose()
		err = errors.Join(err, <-closed)
		if err == nil {
			fmt.Println("Service.Close: completed")
		}
	}()

	port, err := service.Port()
	if err != nil {
		return err
	}
	base := fmt.Sprintf("http://127.0.0.1:%d", port)
	transport := &http.Transport{DisableKeepAlives: true}
	defer transport.CloseIdleConnections()
	client := &http.Client{Transport: transport}

	first := make(chan reply, 1)
	go func() { first <- get(ctx, client, base+"/held") }()
	select {
	case <-entered:
		fmt.Println("GET /held: handler entered and waiting")
	case result := <-first:
		return fmt.Errorf("held request ended before entering the handler: %+v", result)
	case <-ctx.Done():
		return ctx.Err()
	}

	startClose()
	health, err := waitForAdmissionToClose(ctx, service)
	if err != nil {
		return fmt.Errorf("observe drain: %w", err)
	}
	if health.Ready {
		return errors.New("service still reports ready after admission closed")
	}
	fmt.Printf("During drain: ready=%t admission_open=%t\n", health.Ready, health.AdmissionOpen)

	probeCtx, stopProbe := context.WithTimeout(ctx, time.Second)
	defer stopProbe()
	probe := get(probeCtx, client, base+"/new")
	switch {
	case errors.Is(probe.err, syscall.ECONNREFUSED):
		fmt.Println("GET /new: connection refused")
	case probe.err == nil && probe.status == http.StatusServiceUnavailable:
		fmt.Println("GET /new: HTTP 503")
	default:
		return fmt.Errorf("expected new request refusal, got status=%d error=%v", probe.status, probe.err)
	}
	if newHandlerCalls.Load() != 0 {
		return errors.New("a new request reached its handler during drain")
	}

	releaseHandler()
	select {
	case result := <-first:
		if result.err != nil || result.status != http.StatusOK || result.body != heldBody {
			return fmt.Errorf("held request did not finish: %+v", result)
		}
		fmt.Printf("GET /held: HTTP %d, %s", result.status, result.body)
	case <-ctx.Done():
		return ctx.Err()
	}
	return nil
}

func main() {
	if err := run(); err != nil {
		log.Fatal(err)
	}
}
Terminal
go mod init example.com/coakka-http-drain
go get github.com/phuong-tran/coakka-http-runtime-go/[email protected]

export COAKKA_HTTP_SDK=/absolute/path/to/sdk
export CGO_CFLAGS="-I$COAKKA_HTTP_SDK/include"
export CGO_LDFLAGS="-L$COAKKA_HTTP_SDK/lib -Wl,-rpath,$COAKKA_HTTP_SDK/lib"
CGO_ENABLED=1 go run drain.go

Output on Mac ARM64 with Go connector 2.3.1 and SDK 2.3.0

GET /held: handler entered and waiting
During drain: ready=false admission_open=false
GET /new: connection refused
GET /held: HTTP 200, held request finished
Service.Close: completed

Read the Health snapshot

09 · Stop is not destroy

After stop, the owner and queued observations may still exist

Stop

Ends/joins the Core protocol owner under the finite contract and closes completion admission. Inspect status; a call attempt is not success.

Queued observations

Terminal observations can remain readable after stop. Explicit destroy may abandon delivery but cannot bypass a borrowed lease.

Borrowed leases

Every successful take owns a native lease until matching release. Stop/cancel never turns a borrowed pointer into application-owned memory.

Application resources

Handler/downstream state is freed only after no request/session/task/callback can reference it; Core drain proof does not cover every app reference.

10 · Checked destruction

Destroy failure preserves the owner; there is no “best effort free”

service owner is non-null
  → stop/join or let checked destroy perform required stop
  → retire queued terminal delivery per contract
  → release every caller-borrowed native lease
  → destroy(&service)

OK      → service becomes null; native owner is gone
failure → service stays non-null; release/recover and retry
null owner value → idempotent OK
null pointer-to-owner → invalid argument

Serialize destroy with every other operation. Never race destroy against take/respond/monitor/control, drop the pointer after timeout or let a language finalizer hide close failure.

11 · Process and deployment boundary

Importing a connector must not silently seize process signals

12 · Shutdown failures

Timeout preserves ambiguity and ownership

FailureNever doSafe action
Drain pending/expiredReport graceful complete or free handler state.Record state, apply outer policy and preserve terminal/business ambiguity.
Reader/waiter does not joinDestroy the service under a reading thread.Interrupt the correct lane, bounded-join, retain owner and diagnose.
Borrowed lease remains liveDrop the pointer or let GC/finalizer guess.Release the matching lease; retry checked destroy.
Stop/destroy failureNull the owner, swallow error or mark rollout success.Keep owner reachable, attach cleanup error and escalate visibly.
Lost response after effectRetry business work merely because of shutdown/timeout.Use idempotency/reconciliation and client retry policy.

13 · Sizing and evidence

Tune from workload and device budget, not intuition

14 · Integration checklist

Before choosing a language API