Declare intent
The builder/host supplies required capabilities, limits and optional startup reservations.
Product knowledge · Advanced · Operations
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
max_requests knob| Boundary | Finite shape to account for | Owner |
|---|---|---|
| Routes + live control | Route/segment/capture/metadata bytes, activation receipts, control queue/history and commands per turn. | Core reservation; App Host retains bounded prepared/draining handlers. |
| Listener + admission | Connections, active requests, request/completion queues, completion batch and terminal queue. | CoAkka HTTP Runtime. |
| Request + response | Header count/bytes, target/body bytes, retained values and completion lifetime. | Core at wire/admission; connector/application for copied values. |
| Request/response streams | Chunk slots/bytes, retained items/per-stream/total bytes, trailers and write/progress deadline. | Core slots; application producer/consumer queues. |
| Files + compression | Mount/assets/authorities, active reads, response bytes and compression eligibility/output/workspace. | Core delivery; application authorization; deployment bytes. |
| SSE + WebSocket | Sessions, frame/event/message bytes, pending output, source backlog and reconnect/drain window. | Core protocol; application event/session policy. |
| Outbound HTTP | Target/endpoint/trust/identity sets, DNS/pools, in-flight calls, redirects, responses and terminals. | Core transport; application business retry/idempotency. |
| Monitor + inspection | Event ring/page, failure rows, latency buckets, inspection response/cache and exporter queue. | Core reservation; application exporter; deployment exposure. |
| Application dependencies | Executors/tasks/goroutines, database pools, caches, retries, handler state and shutdown hooks. | Application/App Host; never a hidden Core queue. |
02 · Requested versus effective
The builder/host supplies required capabilities, limits and optional startup reservations.
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.
Core resolves zero/dependent defaults once, validates relationships/capacity and fails closed for an invalid candidate.
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 | Representative effective fields |
|---|---|
| Route/control | max_routes, total segments/route bytes/metadata, captures, activation history, route-control capacity/history/commands per turn. |
| Admission/terminal | max_connections, max_active_requests, request/completion/terminal queue capacity and completion batch. |
| HTTP values | Header count/bytes and request/response body bytes. |
| Stream retention | Request/response chunk slots, max chunk/trailer bytes, retained items and per-stream/total retained bytes. |
| Scheduling | Deadline tick, connection-timeout batch and request/terminal notification profiles. Event-loop CPU mask is placement intent, not process CPU quota/thread count. |
| Progress deadlines | Keep-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
| Outcome | Meaning | Next action |
|---|---|---|
| Pressure / capacity exhausted | A finite slot/queue is full now. | Back off, shed/refuse or tune from evidence; never create a hidden queue. |
| Limit | An item/byte count exceeds an accepted ceiling. | Change the input/contract or replacement reservation; identical retry cannot help. |
| Timeout | The correct phase's progress deadline expired. | Preserve phase/certainty; never infer business effect or cleanup rollback. |
| Cancellation | Peer/application/lifecycle requested owned work to stop. | Stop producer/downstream work, wait for the matching terminal, then clean up. |
| Closed | The surface no longer admits this operation in its lifecycle. | Do not resubmit to a stopped owner; finish release/rollout at the correct scope. |
| Unsupported | The exact package/adapter/target does not expose the capability. | Feature-check and choose a supported path; never silently fall back. |
| Application/service failure | Handler/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
Listener/admission decides before the handler; a body limit does not collect more and refuse later.
If a connector has a queue, bound both items and retained bytes. Otherwise active-handler/event-loop admission is the bound.
Producers write only when writable, use a finite progress deadline and stop on cancel/disconnect/drain.
DB pools, task queues, caches, retries and exporters have their own pressure policy; Core never absorbs overload for the application.
06 · Time scopes
Use monotonic time for progress budgets. Wall-clock changes must not make a request/drain live forever or expire early.
07 · Ordered shutdown
The App Host opts into a process signal/shutdown hook; deployment withdraws the instance from ingress first when rollout requires it.
Core closes new admission by lifecycle. Never stop the request reader/handler before accepted work can progress.
Observe the aggregate native drain barrier within a finite window while handlers, streams and readers keep running.
Stop app producers/downstream/retry, interrupt and join owned waiters by connector contract; Monitor has explicit interrupt.
Stop the protocol/transport owner and completion admission; inspect the typed result. Stop does not free the service.
Consume or intentionally abandon queued results by contract; release every successful borrowed request/WebSocket/outbound event lease.
Serialize destruction. Only completed destroy nulls/frees; refusal preserves the service pointer for cleanup and retry.
08 · Drain observation
| Core state | Meaning |
|---|---|
NOT_STARTED | Drain has not begun; waiting is invalid usage and never starts it implicitly. |
PENDING | The caller's wait window ended but the native barrier has not converged; not a transport timeout or stop. |
COMPLETE | Native work quiesced. It does not prove every exchange succeeded, the peer consumed bytes or queued/borrowed results were released. |
EXPIRED | Unfinished native work was forced at the Core drain deadline; preserve failure/terminal evidence. |
ABORTED | Drain was closed/aborted by lifecycle; this is not graceful success. |
FAILED | The barrier produced no complete fact; retain the owner and structured evidence. |
UNSUPPORTED | The 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.
Study · Go
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.
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)
}
}
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.goOutput 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
ready=false and admission_open=false come from Service.Health(). The instance has stopped accepting new traffic.Service.Close() succeeds.09 · Stop is not destroy
Ends/joins the Core protocol owner under the finite contract and closes completion admission. Inspect status; a call attempt is not success.
Terminal observations can remain readable after stop. Explicit destroy may abandon delivery but cannot bypass a borrowed lease.
Every successful take owns a native lease until matching release. Stop/cancel never turns a borrowed pointer into application-owned memory.
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
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 argumentSerialize 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
12 · Shutdown failures
| Failure | Never do | Safe action |
|---|---|---|
| Drain pending/expired | Report graceful complete or free handler state. | Record state, apply outer policy and preserve terminal/business ambiguity. |
| Reader/waiter does not join | Destroy the service under a reading thread. | Interrupt the correct lane, bounded-join, retain owner and diagnose. |
| Borrowed lease remains live | Drop the pointer or let GC/finalizer guess. | Release the matching lease; retry checked destroy. |
| Stop/destroy failure | Null the owner, swallow error or mark rollout success. | Keep owner reachable, attach cleanup error and escalate visibly. |
| Lost response after effect | Retry business work merely because of shutdown/timeout. | Use idempotency/reconciliation and client retry policy. |
13 · Sizing and evidence
14 · Integration checklist