aquifer

package module
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 24, 2026 License: MIT Imports: 32 Imported by: 0

README

Aquifer — MCP Traffic Framework

Increase your rate limit without DDoSing your backend.

Aquifer is a self-hosted agent-native load balancer and traffic coordination layer for agent workloads. It absorbs bursts into a durable queue, dispatches at a controlled rate, and spreads traffic across a pool of registered backend instances. Upstreams can dynamically slow Aquifer down with X-Aqueduct-* response headers, so an overloaded service can shed pressure before it starts returning 429s.

Exposed through pluggable adapters — an MCP server for agent tool-calling, a plain HTTP API, or an A2A (Agent2Agent protocol) agent — with cryptographic agent identity via the L8 protocol for trustless webhook delivery.

Benchmarked: 10x traffic spikes absorbed with zero failures, 30/30 jobs surviving a kill -9 mid-drain, and clean 429 admission shedding under sustained overload — including a real GPU under load, where the ORCA fallback signal cut peak backend queue depth from 449 to 8 waiting requests. See benchmark.md for throughput ceilings, crash recovery, memory behavior, capacity by machine size, and the GPU/vLLM run.


The problem

Distributed agents call tools and APIs in bursts. Your backend gets overwhelmed on inbound. Your app gets 429s on outbound. One slow dependency takes everything else down with it.

Aquifer gives those agents a coordination layer. It absorbs the burst, queues requests durably (SQLite by default, or Pebble — see below), and releases them at the rate you configure. The destination service can ask for a slower pace, and Aquifer honors whichever limit is lower.


Use cases

MCP tools — coordinate distributed agents

agents / MCP clients  →  aquifer_enqueue_job  →  Aquifer queue  →  target API

Agents call Aquifer as an MCP server instead of racing each other directly against the same backend or external API. Aquifer returns a job id immediately, dispatches the request at a controlled rate, and delivers the result to your webhook.

HTTP API — protect your API

agents / clients  →  POST /jobs to Aquifer  →  your backend (at controlled RPS)

Agents hammering your API over HTTP? Aquifer queues their requests and drains them to your backend at a pace it can handle. Your backend returns X-Aqueduct-Rps headers to signal how fast it wants traffic in real time.

Outbound — respect external APIs

your app  →  POST /jobs to Aquifer  →  OpenAI / Stripe / any API (at controlled RPS)

Calling a rate-limited upstream? Aquifer queues the calls and dispatches them at your configured rate. If the upstream signals a slowdown via headers, Aquifer backs off automatically.

In all three, the upstream can lower the dispatch pace via response headers — see Dynamic Pacing for how the ceiling, backoff, and recovery actually work.

Long-term protocol goal: if more services emit X-Aqueduct-*, agents can respond to capacity signals instead of independently guessing retry and concurrency behavior. Aquifer works today without ecosystem adoption; broader protocol adoption is the longer-term goal.


How it works

  1. Client submits a job through an adapter (MCP tool or HTTP endpoint) and moves on
  2. Aquifer persists it to SQLite — survives crashes, re-dispatches on restart
  3. A per-upstream worker dispatches at your configured RPS with jitter
  4. On completion Aquifer POSTs your webhook with the response body and status
  5. The upstream can adjust the rate live via X-Aqueduct-* response headers

Delivery semantics: Aquifer provides at-least-once dispatch and webhook delivery, not exactly-once execution. If Aquifer crashes after a dispatch succeeds but before it records that completion, the recovered job dispatches to the upstream again on restart — so it's not just the webhook that can repeat, the upstream call itself can. Make both your upstream endpoint and your webhook handler idempotent on job_id (or idempotent_key) anywhere duplicate execution isn't safe, the same contract Stripe and GitHub webhooks already ask of you.


Quick start

Binary

go install github.com/rjpruitt16/aquifer/cmd/aquifer@latest
aquifer

Docker

docker run -p 8080:8080 -v $(pwd)/data:/data \
  -e AQUIFER_ADAPTER=http \
  -e DB_PATH=/data/aquifer.db \
  ghcr.io/rjpruitt16/aquifer

Fly.io

git clone https://github.com/rjpruitt16/aquifer
cd aquifer
flyctl launch --name my-aquifer --no-deploy
flyctl volumes create aquifer_data --size 1 --region iad
flyctl deploy

Configuration

Set CONFIG_PATH to a YAML file to configure rate limits per upstream hostname:

# aquifer.yml — copy from aquifer.example.yml
defaults:
  rps: 2
  max_concurrent: 1

upstreams:
  api.openai.com:
    rps: 10
    max_concurrent: 3
  api.stripe.com:
    rps: 20
    max_concurrent: 5
  your-backend.internal:
    rps: 50
    max_concurrent: 10
Env var Default Description
AQUIFER_ADAPTER http for binary, mcp-stdio in Docker image Runtime adapter: http, mcp-stdio, or a2a
AQUIFER_A2A_PUBLIC_URL http://localhost:$PORT A2A adapter only — externally-reachable base URL advertised in the Agent Card
PORT 8080 HTTP listen port
DB_PATH aquifer.db Storage path — a SQLite file, or a directory if AQUIFER_STORE_BACKEND=pebble
CONFIG_PATH (none) Path to rate limit config YAML
AQUIFER_STORE_BACKEND sqlite Storage engine: sqlite or pebble (opt-in, pure-Go LSM store — see benchmark.md for why you might want it)
AQUIFER_PEBBLE_WAL_SYNC_INTERVAL_MS 5 Pebble only — batches concurrent durable writes into fewer real fsyncs under load (Pebble's own group-commit); each caller still blocks until its own write is actually durable
AQUIFER_MEMORY_LIMIT_MB (none, disabled) Reject new jobs with 429 once process memory exceeds this many MB
AQUIFER_MAX_BODY_BYTES 1048576 (1MB) Reject oversized request bodies with 413
AQUIFER_DB_MAX_BYTES 838860800 (800MB) Reject new jobs with 429 once the SQLite file exceeds this size
AQUIFER_RETRY_AFTER_SECONDS 5 Base Retry-After value sent on 429 admission rejections

Body-size and DB-size admission are on by default; memory admission stays off until you set a limit, since a safe default depends on your own deployment, not Aquifer's disk usage. Retry-After backs off exponentially under sustained rejection (5s → 10s → 20s → 40s → capped at 60s, resets on the next allowed request). See CONFIGURATION.md for the full rationale and benchmark.md for the numbers behind these defaults.


Framework adapters

Aquifer has a framework-neutral core and adapter front doors. The core owns idempotency, persistence, rate control, dispatch, SSE events, L8 signing, and webhook delivery. Adapters translate framework-specific calls into that core.

type FrameworkAdapter interface {
    Name() string
    Start(ctx context.Context, aquifer *Aquifer) error
}

Current adapters:

Adapter Env Purpose
HTTP AQUIFER_ADAPTER=http Existing REST/SSE API on PORT
MCP stdio AQUIFER_ADAPTER=mcp-stdio MCP server exposing Aquifer tools over stdio
A2A AQUIFER_ADAPTER=a2a Agent2Agent protocol (v1.0) agent over JSON-RPC/HTTPS on PORT

Run as an MCP stdio server:

AQUIFER_ADAPTER=mcp-stdio aquifer

The published Docker image defaults to AQUIFER_ADAPTER=mcp-stdio so MCP directories such as Glama can start and introspect it directly. Set AQUIFER_ADAPTER=http when running Aquifer as an HTTP queue service.

MCP tools:

Tool Purpose
aquifer_enqueue_job Queue an HTTP request for durable, rate-controlled dispatch
aquifer_get_job Fetch job status and metadata
aquifer_health Return health and protocol metadata
aquifer_l8_metadata Return L8 public key metadata
aquifer_l8_challenge Answer an L8 challenge

MCP resource: aquifer://jobs/{job_id} reads current job status and metadata as JSON. The HTTP adapter remains the default for the binary, so existing deployments do not change.

A2A adapter

Run as an A2A agent (JSON-RPC/HTTPS only for v1 — gRPC and REST bindings aren't wired up):

AQUIFER_ADAPTER=a2a AQUIFER_A2A_PUBLIC_URL=http://localhost:8080 aquifer

AQUIFER_A2A_PUBLIC_URL is the externally-reachable base URL to advertise in the Agent Card — it defaults to http://localhost:$PORT, which is only correct for local use; set it explicitly behind any proxy or real deployment. The Agent Card is served at /.well-known/agent-card.json (the standard A2A convention); send a SendMessage/SendStreamingMessage request whose message contains a single data part shaped like JobRequest (user_id, idempotent_key, url or pool_id, method, headers, body) — the same structured-JSON shape MCP's aquifer_enqueue_job tool already takes. The upstream response comes back as a task artifact. CreateTaskPushNotificationConfig is supported (backed by the SDK's SSRF-hardened HTTP sender); CancelTask deliberately returns an unsupported-operation error rather than a silent no-op, since Aquifer has no real job-cancellation mechanism yet. See a2aadapter/a2a_adapter.go for the full translation between A2A's task model and Aquifer's Enqueue/SubscribeJob.

Writing an adapter

Adapter authors import Aquifer as a Go package, implement FrameworkAdapter, and pass the shared core into their framework — see ADAPTERS.md for the interface, a complete example, and how to reuse Aquifer's runtime wiring in a custom binary. examples/custom_adapter has a compile-tested reference implementation.

Writing a storage backend

Persistence is also pluggable. Every core component (Registry, AccountQueue, URLWorker, Aquifer itself) is coded against the JobStore interface, not the concrete SQLite/Pebble types:

type JobStore interface {
    Path() string
    Close() error
    CheckOrInsert(job *Job) (string, bool)
    SetQueueKey(jobID, queueKey string)
    DeleteJob(jobID string)
    MarkInFlight(jobID string)
    RecoverInFlight(queueKey string) []*Job
    UpdateStatus(jobID string, status Status)
    Counts() StoreCounts
    GetJob(jobID string) *Job
    GetQueuedJobs() []*Job
}

Implement it against your own backend (Postgres, rqlite, or anything else that can give you atomic check-and-set) and pass it via RuntimeOptions.Store — no need to bypass NewRuntime/RunAdapter or hand-wire the lower-level constructors. Two things a custom backend should be aware of: CheckOrInsert needs the same atomicity guarantee SQLite's INSERT OR IGNORE and Pebble's own store give it today (a non-atomic check-then-write reintroduces the exact idempotency race this project has already found and fixed twice — once in each language); and AQUIFER_DB_MAX_BYTES admission control does a local os.Stat on DB_PATH, which is meaningless for a networked backend — set it to 0 to disable that check if your store isn't a local file or directory.

Aquifer doesn't ship a Postgres or rqlite backend itself — this is documented as an extension point for anyone who wants multi-instance durability without local-disk-per-instance, not a promise one exists yet.

Metrics adapter

Aquifer emits lifecycle events through a pluggable metrics adapter — implement MetricsAdapter and pass it into NewRegistry:

type MetricsAdapter interface {
    JobQueued(userID, upstream string)
    JobDispatched(userID, upstream string)
    JobCompleted(userID, upstream string, durationMs int64)
    JobFailed(userID, upstream string, reason string)
    WebhookDelivered(url string, attempt int)
    WebhookFailed(url string, attempts int)
    QueueDepth(upstream string, depth int)
    FlowRate(upstream string, rps float64)
}

Aquifer ships with NoopMetricsAdapter, so existing deployments do not change.


Dynamic Pacing

Terminology: Aquifer is this implementation; Aqueduct is the implementation-agnostic header protocol (X-Aqueduct-*) it speaks, so other services could speak it too.

The upstream controls pace at runtime via response headers. X-Aqueduct-* is the protocol namespace; X-Aquifer-* remains supported as a backward-compatible product alias.

Header (preferred) Alias Effect
X-Aqueduct-Rps X-Aquifer-Rps Reduce dispatch rate to this value
X-Aqueduct-Max-Concurrent X-Aquifer-Max-Concurrent Reduce max in-flight requests
X-Aqueduct-Account-Queue X-Aquifer-Account-Queue enabled — isolate each tenant's queue

Aquifer reads both namespaces, preferring X-Aqueduct-* when both are present.

With X-Aqueduct-Account-Queue: enabled, each (user_id, api_key) pair gets its own independently paced queue, so one tenant's burst can't slow down another. Each queue's pace still stays inside the upstream's actual budget — a background check throttles the sum of every active tenant queue proportionally if too many are active at once, so isolation never means an unbounded copy of the full rate per tenant.

A backend can lower RPS at any time via these headers when it's under pressure; Aquifer honors the lower pace immediately and recovers gradually toward the configured ceiling once pressure clears.

Use the pacing headers for intentional backpressure. A 5xx response is treated as a failed dispatch attempt and, for pool members, lowers that member's reputation. If a service is alive but overloaded, prefer 429 and/or X-Aqueduct-Rps / X-Aqueduct-Max-Concurrent so Aquifer slows down without interpreting the member as broken.

ORCA fallback for backends that can't speak Aqueduct directly. Some backends already report load in a different, real open standard — ORCA (Open Request Cost Aggregation), the gRPC/Envoy ecosystem's convention for backends to report utilization. vLLM supports this natively over plain HTTP: Aquifer sends endpoint-load-metrics-format: TEXT on every dispatch (the request-side opt-in current vLLM actually requires — there's no server startup flag for this), and a vLLM backend that understands it replies with an endpoint-load-metrics header carrying a kv_cache_usage_perc utilization fraction. If a response carries no X-Aqueduct-Rps/X-Aquifer-Rps, Aquifer reads this header as a fallback and paces down as KV-cache usage rises: full configured rate below 70%, 2 RPS at 70-90%, 0.5 RPS at 90-97%, 0.25 RPS above that — never dropping to zero, same pacing-down-gracefully philosophy as everywhere else. An explicit X-Aqueduct-Rps always wins if present; this only fires when the backend hasn't opted into speaking Aqueduct's own headers.


API

POST /jobs
{
  "user_id":        "user-123",
  "idempotent_key": "invoice-42-notify",
  "url":            "https://api.openai.com/v1/chat/completions",
  "method":         "POST",
  "headers":        { "Authorization": "Bearer sk-..." },
  "body":           "{\"model\":\"gpt-4o\",\"messages\":[...]}",
  "webhook_url":    "https://yourapp.com/webhooks/aquifer"
}

Do not expose Aquifer directly to untrusted callers. url is dispatched as a real HTTP request — if an arbitrary or untrusted party can set it, Aquifer becomes an open relay/SSRF vector: it can be pointed at your internal network, cloud metadata endpoints (169.254.169.254), or anything else the machine Aquifer runs on can reach, using Aquifer's own network position and identity. The intended caller is your own trusted backend or gateway code dispatching to a destination it already knows about — not an agent, end user, or any other party choosing the destination itself. Run Aquifer on a private network, not bound to a public address, and put your own authorization and destination allow-listing in front if agents need to reach it indirectly.

Idempotent — duplicate idempotent_key per user_id returns the existing job.

201 new job queued · 200 + "duplicate": true already exists

GET /jobs/:id
{
  "job_id":     "a3f9...",
  "status":     "queued | in_flight | completed | failed",
  "url":        "https://api.openai.com/v1/chat/completions",
  "method":     "POST",
  "created_at": 1715000000000
}
GET /jobs/:id/stream

Server-Sent Events stream for live job updates: queued → dispatching → completed ({"job_id","response_status","body"}) or failed ({"job_id","reason"}), plus a position event every 2s while queued. Connecting late is safe — you'll receive synthetic catchup events for states you missed. SSE is a convenience, not the source of truth: the webhook fires regardless of whether the stream was ever open.

curl -N http://localhost:8080/jobs/<id>/stream
GET /health
{
  "status": "ok",
  "l8_protocol": "0.1",
  "l8_public_key": "...",
  "admission": {
    "enabled": true,
    "memory_mb": 42,
    "memory_limit_mb": 400,
    "max_body_bytes": 1048576,
    "db_bytes": 81920,
    "db_max_bytes": 104857600,
    "retry_after_seconds": 5
  }
}

admission.enabled is false (with only that key present) when none of the AQUIFER_* admission env vars are set.

Webhooks

Completed

{
  "job_id":          "a3f9...",
  "status":          "completed",
  "response_status": 200,
  "body":            "..."
}

Failed (after 4 retries with exponential backoff)

{
  "job_id": "a3f9...",
  "status": "failed",
  "reason": "connection refused"
}

Webhook delivery uses the same account-queue pacing as forward dispatch. A webhook POST isn't fired immediately from the dispatch goroutine — it's enqueued as its own durable job, keyed by the webhook receiver's domain, and dispatched through the identical AccountQueue/URLWorker machinery described in Dynamic Pacing above. Practically, this means:

  • A webhook receiver can slow Aquifer down with the same X-Aqueduct-Rps / X-Aqueduct-Max-Concurrent response headers a real upstream uses, instead of just getting hammered.
  • Delivery is crash-durable — a webhook still pending when the process restarts is recovered and retried, the same way a queued job is, rather than being lost with an in-memory retry loop.
  • Retries trigger on 5xx responses (not every non-2xx), matching forward dispatch's own retry condition — up to 4 attempts, exponential backoff 1 s · 2 s · 4 s · 8 s.
  • L8 signing (below) still applies exactly as before — trust is established and delivery is signed the same way, just from inside the paced dispatch path instead of a separate one-shot retry loop.

Delivery is still at-least-once — see Delivery semantics above. (Drain mode's own ledger-flush webhook is unaffected — it stays synchronous, confirming delivery before clearing the local idempotency ledger.)


Autoscaling

Traditional load balancers and autoscalers rely on failure to start scaling — capacity only responds once something's already struggling. Aquifer treats resources as fluid, not fixed: it paces down as machines show strain and back up as capacity comes online, using the same signals it already reports on every response.

Header Value
X-Aqueduct-Total-Jobs Total jobs on this machine right now
X-Aqueduct-Queue-Depth Jobs waiting to be dispatched
X-Aqueduct-Flow-Rate Current dispatch rate (RPS) for this queue

Agent-native load balancing

Instead of dispatching to a fixed url, a job can target a named pool — a group of registered service instances Aquifer picks from at dispatch time. Useful when you have several interchangeable backends (or, e.g., a separate group of writers and a separate group of readers) instead of one fixed endpoint.

Registering a member:

curl -X POST https://your-aquifer/pools/writers/members \
  -d '{"member_id": "writer-1", "address": "http://10.0.1.5:8080", "capacity_rps": 20, "heartbeat_interval_seconds": 30}'

The same call is both initial registration and heartbeat — call it again periodically (at roughly your declared heartbeat_interval_seconds) to stay in the pool. Missing several consecutive expected heartbeats evicts a member. A member can register under more than one pool id.

Dispatching to a pool:

{
  "user_id": "user-123",
  "idempotent_key": "job-1",
  "pool_id": "writers",
  "method": "POST",
  "webhook_url": "https://yourapp.com/webhooks/aquifer"
}

pool_id and url are mutually exclusive — a job sets exactly one.

How a member gets picked: proportional to capacity_rps × reputation, not equal-split round robin — a member declaring 100 RPS gets roughly 4x the dispatches of one declaring 25. The pool's aggregate ceiling is the live sum of every member's current effective rate, so it grows and shrinks automatically as members register, degrade, or drop out — no need to reconfigure Aquifer as your fleet autoscales.

Reputation: a dispatch failure halves a member's effective share; a successful dispatch nudges it back up, and heartbeats recover it more slowly after a restart. A member isn't evicted on one bad response — only once its reputation has stayed at the floor continuously, with no interrupting success, for a sustained window. This avoids flapping a member in and out of the pool over a single transient error.

Treat 5xx carefully. Aquifer interprets connection errors and 5xx responses as reliability signals for the selected member. One 5xx does not fail the job by itself — Aquifer records failure for that member and retries another member when possible. If every retry across the pool still ends in connection errors or 5xx, the job is marked failed. That behavior is intentional for reliability, but it means application bugs that accidentally return 5xx on a new code path can reduce that member's traffic share or eventually remove it from the pool.

For overload, prefer explicit backpressure over generic server errors:

Situation Recommended signal
Instance is healthy but needs less traffic X-Aqueduct-Rps or X-Aqueduct-Max-Concurrent
Request should be retried later due to pressure 429 with Retry-After
Instance/code path is actually failing 5xx

Roll new members into a pool gradually. Start new versions with a conservative capacity_rps, send a small share of traffic first, watch /health reputation and your own error metrics, then raise capacity as confidence grows. Blue/green or canary rollout matters more here than with a blind round-robin balancer because Aquifer uses runtime failures as routing input.

Set capacity_rps conservatively, not at your true theoretical max. Aquifer only learns a member died via a failed dispatch or a missed heartbeat, both of which lag the actual failure — leaving headroom in what you declare gives real slack for that detection delay. Reputation decay is a second line of defense on top of this: a member that's silently struggling gets throttled down by observed failures even if its last-declared capacity was optimistic.

Watch the model locally: Aquifer includes a local scenario harness that starts one fake backend server with multiple logical workers, registers them as pool members, and prints per-second traffic, failures, dynamic header values, and reputation.

go run ./cmd/aquifer-scenario --scenario mixed --workers 10 --jobs 500 --duration 30s --rps 50

Scenarios: steady, weighted, flapping, backpressure, recovering, mixed, and harsh. The harsh scenario penalizes sustained overload by adding latency, then 5xx, then simulated crash windows. Add --mode regular to compare against a simple round-robin load balancer model that retries on 5xx but ignores Aquifer reputation and dynamic pacing headers.

Pool state isn't shared across Aquifer instances — see Deployment model for how that constrains a given pool_id to one instance.

GET /health reports every pool's current members, their declared capacity, and current reputation.


L8 Protocol — trustless webhook delivery

Traditional webhook security shares an HMAC secret between sender and receiver, stored in a database on both sides — something that can be stolen, logged accidentally, or forgotten during rotation, letting anyone forge deliveries forever once it leaks. Aquifer implements L8 v0.1, a lightweight challenge-response protocol that replaces the shared secret with public key cryptography — there's no secret to steal from a database.

How it works:

  1. The receiver publishes a public key at GET /.well-known/l8
  2. Before the first delivery, Aquifer challenges the receiver to prove ownership of the corresponding private key — a one-time handshake
  3. Trust is cached to disk as l8-trust/{domain}.json — the handshake never runs again for that domain
  4. Every delivery carries X-L8-Signature headers, verified locally with a single Ed25519 call — no database lookup, no round-trip to any authority, microseconds

Trust stays deliberately pairwise, not transitive, by design. For better security and less latency than a shared-secret scheme, see the L8 spec for the full protocol rationale.

Set L8_PRIVATE_KEY (base64 Ed25519 private key) for a stable identity across restarts, or let Aquifer auto-generate one on first start. Delete l8-trust/{domain}.json to revoke trust with a domain — the handshake re-runs on next delivery.

Aquifer exposes:

Endpoint Purpose
GET /.well-known/l8 Aquifer's public key and capabilities — receivers discover Aquifer here
POST /l8/challenge Handles incoming challenges from receivers verifying Aquifer's identity
GET /l8-spec The full L8 protocol spec, served locally for an agent/script with only network access to this instance

Current protocol version 0.1, advertised in /.well-known/l8 and GET /health — the same canonical spec ezthrottle-local follows. A complete reference receiver implementation and end-to-end tests are in tests/l8_receiver.py and tests/test_l8.py.


Reliability

  • Durable queue — jobs persist to the configured storage backend on every write
  • Crash recovery — queued jobs re-dispatched automatically on restart
  • In-flight tracking — jobs marked in_flight before dispatch; recovered immediately on panic without waiting for full restart
  • Stale job safety net — in-flight jobs older than 5 min automatically reset to queued
  • Per-job panic isolation — a panic in one job marks it failed and delivers the webhook; the worker keeps running

Job TTLs:

Status TTL
queued 24 h
completed 30 min
failed 2 h

Drain mode

Off by default. A normal deployment (a single long-lived instance, or static domain/tenant partitioning as described below) is completely unaffected unless you explicitly turn this on — no background watchdog runs, no added overhead, nothing about default behavior changes.

Aquifer's idempotency store exists to dedupe retries while a burst is actively draining, not to be a permanent system of record. Drain mode is for a specific deployment pattern: instances get handed to a tenant, absorb and drain their burst, then get freed for reassignment to a different tenant. When enabled, and an instance goes completely idle (no requests anywhere on the whole process, not just one tenant's queue) for AQUIFER_DRAIN_TIMER_SECONDS, Aquifer flushes everything it's deduped since the last flush to a webhook, and only on confirmed delivery, clears its local ledger — making the instance safe to hand to someone else.

Aquifer does not decide who gets a freed instance next, and does not retain the ledger itself beyond the next flush. That orchestration — durable long-term storage, and assigning tenants to instances — is entirely up to whatever service you build to receive this webhook. Aquifer only detects idle and hands off what it has.

State machine, visible via GET /health ("drain": {"state": "..."}, only present when enabled):

State Meaning
active At least one upstream has live work. Normal state, drain mode enabled or not.
draining Every upstream has gone idle, but either the drain timer hasn't elapsed yet or a flush attempt is in flight/being retried. Not yet safe to hand off.
unassigned The ledger was flushed (or there was nothing to flush) and local state is clear — safe to hand off. Reverts to active the instant new work arrives.

unassigned is a status label, not an access gate — Aquifer keeps accepting new jobs in every state. Nothing stops a job from landing on an instance mid-handoff; if your orchestrator needs a hard guarantee that never happens, enforce it on your own end before routing traffic there.

Env vars:

Var Default Notes
AQUIFER_DRAIN_ENABLED false The real gate — the other two vars are only read when this is true.
AQUIFER_DRAIN_TIMER_SECONDS 45 How long the whole instance must be idle before flushing. Deliberately separate from the unrelated 5-minute per-tenant-queue self-GC timer, which reclaims one queue's memory and has nothing to do with instance-wide handoff.
AQUIFER_DRAIN_WEBHOOK_URL (none) Required if enabled — if unset, drain mode logs a warning and stays off rather than flushing with nowhere to send it.

Webhook payload:

{
  "event": "instance_idle",
  "flushed_at": "2026-08-23T14:02:11Z",
  "ledger": [
    { "idempotent_key_hash": "3fa9c1...", "job_id": "a3f9...", "status": "completed" }
  ]
}

idempotent_key_hash is sha256(user_id + ":" + idempotent_key), hex-encoded lowercase — the exact hash Aquifer already computes internally, never the plaintext key. A downstream consumer re-checking a key for a duplicate must hash it the same way.

If you're also running ezthrottle-local, its drain mode hashes the identical way — both systems share one hash-key namespace for the same (user_id, idempotent_key) pair, so a downstream consumer can hash lookups the same way regardless of which system a given ledger entry came from.


Deployment model

Aquifer runs four ways: as a sidecar alongside your app, as a standalone service multiple services point to, embedded directly as a Go library in your own process (see Framework adapters), or as an extension behind a Gateway API proxy like Envoy Gateway in Kubernetes — the proxy owns routing and TLS, Aquifer owns the queue behind it (see examples/kubernetes). Each instance persists to its own SQLite volume — no external database or coordination service to run.

Scale by partitioning: run one instance per upstream domain or tenant, each owning a distinct key space, and total throughput scales with instance count. Multiple instances against the same upstream without partitioning multiplies your request rate against it instead — the one setup to avoid. The same applies to pools: a given pool_id should belong to exactly one instance, since pool state isn't shared across instances.

This partitioning is static — decided at deploy time, fixed until you redeploy. Drain mode is a dynamic alternative to the same problem: rather than every instance owning a fixed slice forever, an idle instance can flush what it's deduped and hand itself back for reassignment, letting an external orchestrator repartition on the fly as load shifts between tenants instead of you doing it by hand at deploy time. The two aren't mutually exclusive — a fleet can partition statically by upstream domain while individual instances within a partition cycle through tenants dynamically via drain mode.

People run Aquifer in front of things like: internal coding platforms (GitLab, Forgejo), CI runners, database read replicas, and MCP servers — anywhere a burst of agent or service traffic needs to hit something that has its own capacity limit.

See the security warning under POST /jobs — the same untrusted-caller risk applies regardless of deployment shape.


Choosing a machine size

Earlier benchmarks hit an artificial ~200 req/s ceiling caused by a serialized SQLite connection; that bottleneck is fixed. See benchmark.md for current throughput, capacity by machine size, and the benchmark methodology.


Writing

License

MIT

Built by Rahmi Pruitt — open to AI infra consulting, founding engineer, and contract work.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrJobNotFound = errors.New("job not found")

Functions

func RunAdapter

func RunAdapter(ctx context.Context, adapter FrameworkAdapter, opts RuntimeOptions) error

Types

type AccountQueue

type AccountQueue struct {
	// contains filtered or unexported fields
}

func NewAccountQueue

func NewAccountQueue(key, upstream string, rps float64, maxConc int, pool *Pool, store JobStore, broker *Broker, l8 *L8Registry, metrics MetricsAdapter, enqueueWebhook webhookEnqueuer, onIdle func(string)) *AccountQueue

func (*AccountQueue) Enqueue

func (q *AccountQueue) Enqueue(job *Job)

func (*AccountQueue) RPS

func (q *AccountQueue) RPS() float64

func (*AccountQueue) Throttle added in v0.4.0

func (q *AccountQueue) Throttle(rps float64)

Throttle pushes an external rate adjustment into the queue's dispatch loop, reusing the same jobDoneMsg channel that header-driven pacing already uses — the loop doesn't need to know whether a lower rate came from the upstream's own response header or from the URLWorker capping this queue's share of a shared aggregate budget, it's the same signal either way.

type AdmissionController added in v0.3.0

type AdmissionController struct {
	// contains filtered or unexported fields
}

AdmissionController evaluates memory and DB size limits at request time. Body size is enforced separately at the transport layer via http.MaxBytesReader, since that has to happen before the body is even read.

func NewAdmissionController added in v0.3.0

func NewAdmissionController(limits AdmissionLimits, dbPath string) *AdmissionController

func (*AdmissionController) AnyLimitConfigured added in v0.3.0

func (c *AdmissionController) AnyLimitConfigured() bool

AnyLimitConfigured reports whether at least one admission limit is actually active, as opposed to merely whether a controller instance exists (the runtime always constructs one, even with everything at zero).

func (*AdmissionController) Check added in v0.3.0

func (*AdmissionController) MaxBodyBytes added in v0.3.0

func (c *AdmissionController) MaxBodyBytes() int64

func (*AdmissionController) RetryAfterSeconds added in v0.3.0

func (c *AdmissionController) RetryAfterSeconds() int

RetryAfterSeconds returns the configured base value on the first rejection, then doubles for each additional consecutive rejection (capped at maxRetryAfterSeconds), resetting the moment a request is allowed again.

func (*AdmissionController) Snapshot added in v0.3.0

func (c *AdmissionController) Snapshot() map[string]any

Snapshot reports current admission pressure for /health, independent of whether any request is currently being rejected.

type AdmissionDecision added in v0.3.0

type AdmissionDecision struct {
	Allowed bool
	Reason  string // "memory" or "db_size"
	Limit   int64
	Current int64
}

AdmissionDecision is the result of an admission check on a new (non-duplicate) job.

type AdmissionLimits added in v0.3.0

type AdmissionLimits struct {
	MemoryLimitMB     int64 // AQUIFER_MEMORY_LIMIT_MB
	MaxBodyBytes      int64 // AQUIFER_MAX_BODY_BYTES
	DBMaxBytes        int64 // AQUIFER_DB_MAX_BYTES
	RetryAfterSeconds int   // AQUIFER_RETRY_AFTER_SECONDS
}

AdmissionLimits are operator-configured ceilings that protect Aquifer itself from the traffic it's meant to be absorbing. A zero value disables that particular check. Memory is opt-in (LoadAdmissionLimits defaults it to disabled); body size and DB size default on — see LoadAdmissionLimits.

func LoadAdmissionLimits added in v0.3.0

func LoadAdmissionLimits() AdmissionLimits

LoadAdmissionLimits reads the AQUIFER_* admission env vars. Body size and DB size fall back to sane, non-zero defaults when unset (see the default* constants above) rather than being disabled — Aquifer's whole purpose is protecting the process from the traffic it absorbs, so it protects itself by default rather than requiring that to be opted into. An explicit "0" still disables a given check. Memory has no safe one-size-fits-all default (it depends on the deployment's own memory budget, not Aquifer's benchmarked disk usage), so it stays disabled unless set explicitly — LoadAdmissionLimits logs a warning when it is.

type AdmissionRejectedError added in v0.3.0

type AdmissionRejectedError struct {
	Decision AdmissionDecision
}

AdmissionRejectedError is returned by Aquifer.Enqueue when a genuinely new job is rejected due to memory or DB size pressure. Callers (the HTTP server) type-assert on this to build a 429 with Retry-After.

func (*AdmissionRejectedError) Error added in v0.3.0

func (e *AdmissionRejectedError) Error() string

type Aquifer

type Aquifer struct {
	// contains filtered or unexported fields
}

func NewAquifer

func NewAquifer(store JobStore, registry *Registry, broker *Broker, l8 *L8Registry, admission *AdmissionController, pools *PoolRegistry) *Aquifer

func (*Aquifer) AdmissionSnapshot added in v0.3.0

func (a *Aquifer) AdmissionSnapshot() map[string]any

AdmissionSnapshot reports current admission pressure for /health. Returns enabled:false if admission control isn't configured.

func (*Aquifer) Enqueue

func (a *Aquifer) Enqueue(req JobRequest) (EnqueueResult, error)

func (*Aquifer) GetJob

func (a *Aquifer) GetJob(id string) (*Job, error)

func (*Aquifer) HandleL8Challenge

func (a *Aquifer) HandleL8Challenge(req L8ChallengeReq) (*L8ChallengeResp, error)

func (*Aquifer) Health

func (a *Aquifer) Health() map[string]any

func (*Aquifer) L8Metadata

func (a *Aquifer) L8Metadata(host string) L8Meta

func (*Aquifer) MaxBodyBytes added in v0.3.0

func (a *Aquifer) MaxBodyBytes() int64

MaxBodyBytes returns the configured request body ceiling, or 0 if unconfigured (unlimited).

func (*Aquifer) RegisterPoolMember added in v0.4.0

func (a *Aquifer) RegisterPoolMember(poolID, memberID, address string, declaredRPS float64, heartbeatIntervalSeconds int) error

RegisterPoolMember adds or refreshes (heartbeats) a member of a pool. The same call serves both roles — re-registering resets the member's liveness TTL and updates its declared capacity.

func (*Aquifer) RetryAfterSeconds added in v0.3.0

func (a *Aquifer) RetryAfterSeconds() int

RetryAfterSeconds returns the configured Retry-After value for 429 responses, defaulting to 5 seconds if admission control isn't configured.

func (*Aquifer) SubscribeJob

func (a *Aquifer) SubscribeJob(id string) (*Job, <-chan SSEEvent, func(), error)

type Broker

type Broker struct {
	// contains filtered or unexported fields
}

Broker is the pub/sub layer for SSE streams. Each job gets its own set of subscriber channels.

func NewBroker

func NewBroker() *Broker

func (*Broker) Publish

func (b *Broker) Publish(jobID string, event SSEEvent)

func (*Broker) Subscribe

func (b *Broker) Subscribe(jobID string) (<-chan SSEEvent, func())

type Config

type Config struct {
	Defaults  RateConfig            `yaml:"defaults"`
	Upstreams map[string]RateConfig `yaml:"upstreams"`
}

func LoadConfig

func LoadConfig(path string) *Config

func (*Config) ForURL

func (c *Config) ForURL(rawURL string) RateConfig

type DrainConfig added in v0.6.0

type DrainConfig struct {
	Enabled      bool  // AQUIFER_DRAIN_ENABLED
	TimerSeconds int64 // AQUIFER_DRAIN_TIMER_SECONDS
	WebhookURL   string
}

func LoadDrainConfig added in v0.6.0

func LoadDrainConfig() DrainConfig

LoadDrainConfig reads the AQUIFER_DRAIN_* env vars. Enabled defaults to false. If enabled but no webhook URL is configured, that's treated as disabled (with a warning) rather than a flush attempt with nowhere to send it -- fail-safe toward "do nothing," never toward "clear the ledger anyway."

type DrainState added in v0.6.0

type DrainState string

DrainState is the instance's explicit position in drain mode's lifecycle, visible via GET /health (see Registry.DrainSnapshot). Only meaningful when drain mode is enabled.

const (
	// DrainStateActive: at least one worker has live work. The normal
	// state for any instance, drain mode enabled or not.
	DrainStateActive DrainState = "active"
	// DrainStateDraining: every worker has gone idle, but either the drain
	// timer hasn't elapsed yet, or a flush attempt is in flight/being
	// retried. Not yet safe to hand off.
	DrainStateDraining DrainState = "draining"
	// DrainStateUnassigned: the ledger was successfully flushed (or there
	// was nothing to flush) and local state is clear. Safe to hand off to
	// a different tenant. Reverts to Active the instant new work arrives.
	DrainStateUnassigned DrainState = "unassigned"
)

type EnqueueResult

type EnqueueResult struct {
	JobID     string `json:"job_id"`
	Status    Status `json:"status"`
	Duplicate bool   `json:"duplicate,omitempty"`
}

type FrameworkAdapter

type FrameworkAdapter interface {
	Name() string
	Start(ctx context.Context, aquifer *Aquifer) error
}

type HTTPAdapter

type HTTPAdapter struct {
	// contains filtered or unexported fields
}

func NewHTTPAdapter

func NewHTTPAdapter(addr string) *HTTPAdapter

func (*HTTPAdapter) Name

func (a *HTTPAdapter) Name() string

func (*HTTPAdapter) Start

func (a *HTTPAdapter) Start(ctx context.Context, aquifer *Aquifer) error

type Job

type Job struct {
	ID            string            `json:"id"`
	UserID        string            `json:"user_id"`
	IdempotentKey string            `json:"idempotent_key"`
	URL           string            `json:"url,omitempty"`
	PoolID        string            `json:"pool_id,omitempty"`
	Method        string            `json:"method"`
	Headers       map[string]string `json:"headers,omitempty"`
	Body          string            `json:"body,omitempty"`
	WebhookURL    string            `json:"webhook_url"`
	Status        Status            `json:"status"`
	CreatedAt     int64             `json:"created_at"`
}

func NewJob

func NewJob(r *JobRequest) *Job

type JobRequest

type JobRequest struct {
	UserID        string            `json:"user_id"`
	IdempotentKey string            `json:"idempotent_key"`
	URL           string            `json:"url,omitempty"`
	PoolID        string            `json:"pool_id,omitempty"`
	Method        string            `json:"method"`
	Headers       map[string]string `json:"headers,omitempty"`
	Body          string            `json:"body,omitempty"`
	WebhookURL    string            `json:"webhook_url"`

	// AccountQueueMode is never read from the request body — it's set by the
	// HTTP adapter from the X-Aqueduct-Account-Queue / X-Aquifer-Account-Queue
	// request header, the only source of truth for this setting. Empty means
	// "no opinion, leave the upstream's current mode unchanged."
	AccountQueueMode string `json:"-"`
}

func (*JobRequest) Validate

func (r *JobRequest) Validate() string

type JobStore added in v0.4.0

type JobStore interface {
	Path() string
	Close() error
	CheckOrInsert(job *Job) (string, bool)
	SetQueueKey(jobID, queueKey string)
	DeleteJob(jobID string)
	MarkInFlight(jobID string)
	RecoverInFlight(queueKey string) []*Job
	UpdateStatus(jobID string, status Status)
	Counts() StoreCounts
	GetJob(jobID string) *Job
	GetQueuedJobs() []*Job

	// ListIdempotentKeys and ClearIdempotentKeys back drain mode (see
	// drain.go) -- an opt-in feature, off by default, so calling these on
	// a deployment that never enables it is never reached.
	ListIdempotentKeys() []LedgerEntry
	ClearIdempotentKeys()
}

JobStore is the storage backend behind everything that persists a job: idempotency, status transitions, crash recovery, and admission control's db-size check. *Store (SQLite/WAL) is the default and only implementation until now; *PebbleStore is an opt-in alternative for benchmarking whether a memory-first LSM store changes the throughput ceiling the way it did for the Elixir/Mnesia sibling of this project. Selected via AQUIFER_STORE_BACKEND ("sqlite", the default, or "pebble") — existing deployments that don't set it see no change at all.

func NewJobStore added in v0.4.0

func NewJobStore(path string) JobStore

NewJobStore constructs whichever backend AQUIFER_STORE_BACKEND names. path is the same value that used to go straight to NewStore — for SQLite it's a file path, for Pebble it's a directory.

type L8ChallengeReq

type L8ChallengeReq struct {
	ChallengeID     string `json:"challenge_id"`
	Nonce           string `json:"nonce"`
	Timestamp       int64  `json:"timestamp"`
	SenderPublicKey string `json:"sender_public_key"`
	Signature       string `json:"signature"`
}

type L8ChallengeResp

type L8ChallengeResp struct {
	ChallengeID       string `json:"challenge_id"`
	Nonce             string `json:"nonce"`
	ReceiverSignature string `json:"receiver_signature"`
	ReceiverPublicKey string `json:"receiver_public_key"`
}

type L8Meta

type L8Meta struct {
	ProtocolVersion   string   `json:"protocol_version"`
	ServiceName       string   `json:"service_name"`
	PublicKey         string   `json:"public_key"`
	ChallengeEndpoint string   `json:"challenge_endpoint"`
	SupportedAlgos    []string `json:"supported_algorithms"`
	Capabilities      []string `json:"capabilities"`
	SpecURL           string   `json:"spec_url"`
}

type L8Registry

type L8Registry struct {
	PubB64 string // exported so server can embed in responses
	// contains filtered or unexported fields
}

func NewL8Registry

func NewL8Registry(keyPath, trustDir string) *L8Registry

func (*L8Registry) EnsureTrust

func (r *L8Registry) EnsureTrust(webhookURL string)

EnsureTrust runs the L8 handshake with the webhook domain if not already trusted. Silently does nothing if the receiver doesn't support L8 — delivery still proceeds unsigned.

func (*L8Registry) HandleChallenge

func (r *L8Registry) HandleChallenge(req L8ChallengeReq) (*L8ChallengeResp, error)

HandleChallenge verifies the sender's ownership proof and returns Aquifer's signed response.

func (*L8Registry) IsTrusted

func (r *L8Registry) IsTrusted(webhookURL string) bool

IsTrusted returns true if the L8 handshake has been completed for this webhook domain.

func (*L8Registry) Meta

func (r *L8Registry) Meta(host string) L8Meta

func (*L8Registry) SignHeaders

func (r *L8Registry) SignHeaders(body []byte) map[string]string

SignHeaders returns X-L8-* headers to attach to an outgoing webhook delivery.

type LedgerEntry added in v0.6.0

type LedgerEntry struct {
	HashKey string `json:"idempotent_key_hash"`
	JobID   string `json:"job_id"`
	Status  Status `json:"status"`
}

LedgerEntry is one row of the drain-mode idempotency ledger -- hash-only, never the plaintext idempotent key. See drain.go.

type MCPStdioAdapter

type MCPStdioAdapter struct {
	// contains filtered or unexported fields
}

func NewMCPStdioAdapter

func NewMCPStdioAdapter(in io.Reader, out io.Writer) *MCPStdioAdapter

func (*MCPStdioAdapter) Name

func (a *MCPStdioAdapter) Name() string

func (*MCPStdioAdapter) Start

func (a *MCPStdioAdapter) Start(ctx context.Context, aquifer *Aquifer) error

type MetricsAdapter

type MetricsAdapter interface {
	JobQueued(userID, upstream string)
	JobDispatched(userID, upstream string)
	JobCompleted(userID, upstream string, durationMs int64)
	JobFailed(userID, upstream string, reason string)
	WebhookDelivered(url string, attempt int)
	WebhookFailed(url string, attempts int)
	QueueDepth(upstream string, depth int)
	FlowRate(upstream string, rps float64)
	// DrainFlushSucceeded/DrainFlushFailed only ever fire when drain mode
	// is enabled (see drain.go) -- unreached on a deployment that never
	// turns it on.
	DrainFlushSucceeded(instanceKey string, ledgerSize int)
	DrainFlushFailed(instanceKey string, ledgerSize int)
}

type NoopMetricsAdapter

type NoopMetricsAdapter struct{}

func (NoopMetricsAdapter) DrainFlushFailed added in v0.6.0

func (NoopMetricsAdapter) DrainFlushFailed(instanceKey string, ledgerSize int)

func (NoopMetricsAdapter) DrainFlushSucceeded added in v0.6.0

func (NoopMetricsAdapter) DrainFlushSucceeded(instanceKey string, ledgerSize int)

func (NoopMetricsAdapter) FlowRate

func (NoopMetricsAdapter) FlowRate(upstream string, rps float64)

func (NoopMetricsAdapter) JobCompleted

func (NoopMetricsAdapter) JobCompleted(userID, upstream string, durationMs int64)

func (NoopMetricsAdapter) JobDispatched

func (NoopMetricsAdapter) JobDispatched(userID, upstream string)

func (NoopMetricsAdapter) JobFailed

func (NoopMetricsAdapter) JobFailed(userID, upstream string, reason string)

func (NoopMetricsAdapter) JobQueued

func (NoopMetricsAdapter) JobQueued(userID, upstream string)

func (NoopMetricsAdapter) QueueDepth

func (NoopMetricsAdapter) QueueDepth(upstream string, depth int)

func (NoopMetricsAdapter) WebhookDelivered

func (NoopMetricsAdapter) WebhookDelivered(url string, attempt int)

func (NoopMetricsAdapter) WebhookFailed

func (NoopMetricsAdapter) WebhookFailed(url string, attempts int)

type PebbleStore added in v0.4.0

type PebbleStore struct {
	// contains filtered or unexported fields
}

func NewPebbleStore added in v0.4.0

func NewPebbleStore(path string) *PebbleStore

func (*PebbleStore) CheckOrInsert added in v0.4.0

func (s *PebbleStore) CheckOrInsert(job *Job) (string, bool)

CheckOrInsert mirrors Store.CheckOrInsert's contract exactly: :ok for a fresh job, or the existing job ID if the (user_id, idempotent_key) pair was already accepted. The shard lock is what makes this atomic instead of a racy Get-then-Set — see the package doc comment above.

func (*PebbleStore) ClearIdempotentKeys added in v0.6.0

func (s *PebbleStore) ClearIdempotentKeys()

ClearIdempotentKeys wipes both the job: and idem: prefixes -- only ever called by drain mode's watchdog after a successful ledger-flush webhook delivery, never on a normal (non-drain-mode) deployment. Takes every shard lock before wiping so a concurrent CheckOrInsert (which only holds one shard's lock) can't race a mid-wipe read/write and reintroduce a row.

func (*PebbleStore) Close added in v0.4.0

func (s *PebbleStore) Close() error

func (*PebbleStore) Counts added in v0.4.0

func (s *PebbleStore) Counts() StoreCounts

func (*PebbleStore) DeleteJob added in v0.4.0

func (s *PebbleStore) DeleteJob(jobID string)

DeleteJob removes both the job row and its idempotency index entry — dropping only the job: key would leave a dangling idem: entry pointing at a job that no longer exists, the same ghost-row risk DeleteJob exists to prevent on the SQLite side.

func (*PebbleStore) GetJob added in v0.4.0

func (s *PebbleStore) GetJob(jobID string) *Job

func (*PebbleStore) GetQueuedJobs added in v0.4.0

func (s *PebbleStore) GetQueuedJobs() []*Job

func (*PebbleStore) ListIdempotentKeys added in v0.6.0

func (s *PebbleStore) ListIdempotentKeys() []LedgerEntry

ListIdempotentKeys backs drain mode's ledger export. Unlike SQLite, pebbleRecord.Job retains the plaintext IdempotentKey (for unrelated reasons -- see the package doc comment), but this must never surface it: the hash is recomputed the same way CheckOrInsert derives it, and only the hash/job_id/status ever go into the returned LedgerEntry. Excludes webhook-delivery jobs (WebhookURL == "", see Job.isWebhookDeliveryJob) -- those are internal delivery bookkeeping, not real user-submitted work, and have no business appearing in a ledger meant for tenant-handoff dedup.

func (*PebbleStore) MarkInFlight added in v0.4.0

func (s *PebbleStore) MarkInFlight(jobID string)

func (*PebbleStore) Path added in v0.4.0

func (s *PebbleStore) Path() string

func (*PebbleStore) RecoverInFlight added in v0.4.0

func (s *PebbleStore) RecoverInFlight(queueKey string) []*Job

func (*PebbleStore) SetQueueKey added in v0.4.0

func (s *PebbleStore) SetQueueKey(jobID, queueKey string)

func (*PebbleStore) UpdateStatus added in v0.4.0

func (s *PebbleStore) UpdateStatus(jobID string, status Status)

type Pool added in v0.4.0

type Pool struct {
	// contains filtered or unexported fields
}

Pool is one named group of registered members. Selection uses virtual-time weighted round robin: each pick advances the chosen member's virtual position by 1/weight (a higher-weight member advances less per pick, so it comes back to the front of the heap sooner and gets picked proportionally more often), giving O(log n) per dispatch — the naive nginx-style smooth-weighted-round-robin algorithm (recompute every member's running weight on every pick) is O(n) per pick instead; this avoids that by only ever touching the single member actually chosen.

func (*Pool) Pick added in v0.4.0

func (p *Pool) Pick() *PoolMember

Pick selects a member proportional to declared_rate x reputation and advances its virtual position. Returns nil if the pool has no members.

func (*Pool) RecordFailure added in v0.4.0

func (p *Pool) RecordFailure(id string) bool

RecordFailure halves a member's reputation — the same shape as the existing Retry-After backoff (doubles per consecutive event), just applied as a share reduction instead of a delay increase. Once reputation has been at or below the floor continuously for defaultFloorEvictionWindow, the member is evicted. Returns whether this call caused an eviction.

func (*Pool) RecordSuccess added in v0.4.0

func (p *Pool) RecordSuccess(id string)

RecordSuccess nudges a member's reputation back toward full trust and unconditionally clears any in-progress floor-eviction timer — the eviction criterion is sustained badness with zero successes in between, not a numeric reputation threshold held for a duration, so any success resets the clock even if the reputation number itself hasn't recovered above the floor yet.

func (*Pool) Register added in v0.4.0

func (p *Pool) Register(id, address string, declaredRPS float64, heartbeatInterval time.Duration)

Register adds a new member or refreshes an existing one. The same call serves as both initial registration and heartbeat — re-calling it resets LastHeartbeat and updates declared capacity, so a member that wants to lower or raise its reported rate just re-registers.

func (*Pool) Size added in v0.4.0

func (p *Pool) Size() int

func (*Pool) Snapshot added in v0.4.0

func (p *Pool) Snapshot() []map[string]any

func (*Pool) TotalCapacity added in v0.4.0

func (p *Pool) TotalCapacity() float64

TotalCapacity is the live sum of every member's current effective weight — the pool's aggregate ceiling grows and shrinks automatically as members register, degrade, or drop out, rather than being a static number an operator configures once.

type PoolMember added in v0.4.0

type PoolMember struct {
	ID                string
	Address           string
	DeclaredRPS       float64
	HeartbeatInterval time.Duration
	LastHeartbeat     time.Time
	// contains filtered or unexported fields
}

PoolMember is one registered target within a pool — a service instance that pinged in with its own address and declared capacity.

func (*PoolMember) Reputation added in v0.4.0

func (m *PoolMember) Reputation() float64

type PoolRegistry added in v0.4.0

type PoolRegistry struct {
	// contains filtered or unexported fields
}

PoolRegistry owns every named pool. One registry per Aquifer instance.

func NewPoolRegistry added in v0.4.0

func NewPoolRegistry() *PoolRegistry

func (*PoolRegistry) Get added in v0.4.0

func (pr *PoolRegistry) Get(poolID string) *Pool

Get returns the named pool, creating an empty one if nobody has registered to it yet. A job dispatched to a pool that exists but has zero members is a different, correctly-handled state (fails cleanly with "no pool members registered") from a job that isn't pool-backed at all — returning nil here would collapse that distinction and let a pool-backed job silently fall through to a non-pool dispatch path with an empty URL instead.

func (*PoolRegistry) Register added in v0.4.0

func (pr *PoolRegistry) Register(poolID, memberID, address string, declaredRPS float64, heartbeatInterval time.Duration)

func (*PoolRegistry) Snapshot added in v0.4.0

func (pr *PoolRegistry) Snapshot() map[string]any

func (*PoolRegistry) Stop added in v0.4.0

func (pr *PoolRegistry) Stop()

type RateConfig

type RateConfig struct {
	RPS           float64 `yaml:"rps"`
	MaxConcurrent int     `yaml:"max_concurrent"`
}

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

func NewRegistry

func NewRegistry(store JobStore, cfg *Config, broker *Broker, l8 *L8Registry, metrics MetricsAdapter, pools *PoolRegistry) *Registry

NewRegistry reads drain mode's config from AQUIFER_DRAIN_* env vars (LoadDrainConfig) — disabled unless AQUIFER_DRAIN_ENABLED is explicitly set, matching NewPebbleStore's existing precedent of reading its own opt-in env vars internally. Callers wanting a programmatic override (RuntimeOptions.DrainConfig) call ConfigureDrain after construction.

func (*Registry) ConfigureDrain added in v0.6.0

func (r *Registry) ConfigureDrain(cfg DrainConfig)

ConfigureDrain overrides drain mode's config after construction (used by RuntimeOptions.DrainConfig) and starts the watchdog if the override enables it and the constructor-time env-based config hadn't already started one. There is no supported path to stop an already-running watchdog at runtime — disabling drain mode requires a restart, same as every other env-var-driven config in this codebase.

func (*Registry) DrainSnapshot added in v0.6.0

func (r *Registry) DrainSnapshot() map[string]any

DrainSnapshot reports drain mode's current state for GET /health, or nil when drain mode isn't enabled — an instance that never turned this on shouldn't see a new key appear in its health output.

func (*Registry) DrainState added in v0.6.0

func (r *Registry) DrainState() DrainState

DrainState is the instance's current position in drain mode's lifecycle (active/draining/unassigned) — meaningful only when drain mode is enabled, but always safe to call (returns DrainStateActive otherwise, since the watchdog that would ever move it elsewhere never runs).

func (*Registry) Enqueue

func (r *Registry) Enqueue(job *Job, accountQueueHeader string)

Enqueue queues a job on the URLWorker for its upstream domain, or for its target pool if the job carries a PoolID instead of a URL. accountQueueHeader is the raw X-Aqueduct-Account-Queue/X-Aquifer-Account-Queue value from the originating HTTP request, or "" if this job has no live request behind it (e.g. recovered from disk at startup). An empty value leaves the worker's current account-queue mode unchanged rather than forcing it off — the mode is shared per upstream domain, so one request that doesn't care about it shouldn't be able to flip it off for every other concurrent tenant relying on it being on.

func (*Registry) EnqueueWebhook added in v0.7.0

func (r *Registry) EnqueueWebhook(originalJobID, userID, webhookURL string, payload map[string]any)

EnqueueWebhook queues a webhook delivery through the same domain-keyed account-queue pacing and backpressure machinery as forward dispatch (RPS/concurrency limits, X-Aqueduct-* response-header throttling) instead of firing immediately with a fixed retry schedule — a slow or rate-limited webhook receiver can now shed load exactly the way an upstream API already can, and delivery is durable across a restart the same way a real job is (the underlying webhook-delivery Job is persisted via CheckOrInsert, not just an in-memory retry loop).

originalJobID scopes the idempotent key (see Job.isWebhookDeliveryJob) so a given job's webhook is enqueued at most once even if this were somehow called twice for it.

func (*Registry) JobDispatched

func (r *Registry) JobDispatched()

func (*Registry) JobDone

func (r *Registry) JobDone()

type Runtime

type Runtime struct {
	Aquifer   *Aquifer
	Store     JobStore
	Broker    *Broker
	Registry  *Registry
	L8        *L8Registry
	Config    *Config
	Admission *AdmissionController
	Pools     *PoolRegistry
}

func NewRuntime

func NewRuntime(opts RuntimeOptions) *Runtime

func (*Runtime) DBPath

func (r *Runtime) DBPath() string

func (*Runtime) RecoverQueuedJobs

func (r *Runtime) RecoverQueuedJobs(dbPath string)

type RuntimeOptions

type RuntimeOptions struct {
	DBPath          string
	ConfigPath      string
	Config          *Config
	L8KeyPath       string
	L8TrustDir      string
	Metrics         MetricsAdapter
	AdmissionLimits *AdmissionLimits
	// Store overrides the storage backend entirely. If nil, NewRuntime falls
	// back to NewJobStore(DBPath), selecting sqlite/pebble via
	// AQUIFER_STORE_BACKEND as before. Set this to plug in a custom JobStore
	// implementation (e.g. Postgres, rqlite) without needing to bypass
	// NewRuntime and wire the lower-level constructors by hand.
	Store JobStore
	// DrainConfig overrides drain mode's config (see drain.go). If nil,
	// the Registry reads AQUIFER_DRAIN_* env vars itself — disabled unless
	// AQUIFER_DRAIN_ENABLED is explicitly set to true.
	DrainConfig *DrainConfig
}

type SSEEvent

type SSEEvent struct {
	Event string
	Data  map[string]any
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer(aquifer *Aquifer) *Server

func (*Server) Routes

func (s *Server) Routes() http.Handler

type Status

type Status string
const (
	StatusQueued    Status = "queued"
	StatusInFlight  Status = "in_flight"
	StatusCompleted Status = "completed"
	StatusFailed    Status = "failed"
)

type Store

type Store struct {
	// contains filtered or unexported fields
}

func NewStore

func NewStore(path string) *Store

func (*Store) CheckOrInsert

func (s *Store) CheckOrInsert(job *Job) (string, bool)

CheckOrInsert inserts job unless its (user_id, idempotent_key) pair already exists, in which case it reports the existing job's ID as a duplicate. The duplicate/fresh decision is read directly off the INSERT's own RowsAffected, not a follow-up SELECT — a SELECT-after-INSERT here would race under real concurrency (multiple open connections): if the INSERT is still in flight relative to another goroutine's read, or a transient busy-retry delays it, the SELECT can find nothing and this would misreport a brand-new job as an empty-ID "duplicate," silently losing it. RowsAffected==1 is authoritative and atomic: it's exactly the row this call just wrote, no read-your-own-write race possible.

func (*Store) ClearIdempotentKeys added in v0.6.0

func (s *Store) ClearIdempotentKeys()

ClearIdempotentKeys wipes the whole table -- only ever called by drain mode's watchdog after a successful ledger-flush webhook delivery, never on a normal (non-drain-mode) deployment.

func (*Store) Close added in v0.4.0

func (s *Store) Close() error

Close releases the underlying connection pool. In WAL mode, SQLite keeps -wal/-shm files alongside the main database file for as long as any connection is open; callers that manage a Store's lifetime explicitly (tests especially, cleaning up a t.TempDir()) should call this before their directory is removed.

func (*Store) Counts

func (s *Store) Counts() StoreCounts

func (*Store) DeleteJob added in v0.3.0

func (s *Store) DeleteJob(jobID string)

DeleteJob removes a job row outright. Used when a freshly-inserted, non-duplicate job is rejected by admission control — CheckOrInsert already wrote the row before duplicate status was known, so a rejected job must be deleted here or it would sit as a ghost "queued" row that never dispatches.

func (*Store) GetJob

func (s *Store) GetJob(jobID string) *Job

func (*Store) GetQueuedJobs

func (s *Store) GetQueuedJobs() []*Job

func (*Store) ListIdempotentKeys added in v0.6.0

func (s *Store) ListIdempotentKeys() []LedgerEntry

ListIdempotentKeys backs drain mode's ledger export -- hash-only, matches what this table has always stored (the plaintext idempotent key was never persisted here, only its hash, see hashKey/CheckOrInsert). Excludes webhook-delivery jobs (webhook_url = ”, see Job.isWebhookDeliveryJob) -- those are internal delivery bookkeeping, not real user-submitted work, and have no business appearing in a ledger meant for tenant-handoff dedup.

func (*Store) MarkInFlight

func (s *Store) MarkInFlight(jobID string)

func (*Store) Path

func (s *Store) Path() string

func (*Store) RecoverInFlight

func (s *Store) RecoverInFlight(queueKey string) []*Job

func (*Store) SetQueueKey

func (s *Store) SetQueueKey(jobID, queueKey string)

func (*Store) UpdateStatus

func (s *Store) UpdateStatus(jobID string, status Status)

type StoreCounts

type StoreCounts struct {
	TotalJobs  int64
	QueueDepth int64
}

type URLWorker

type URLWorker struct {
	// contains filtered or unexported fields
}

func NewURLWorker

func NewURLWorker(domain string, rps float64, maxConc int, pool *Pool, store JobStore, broker *Broker, l8 *L8Registry, metrics MetricsAdapter, enqueueWebhook webhookEnqueuer, onIdle func(string)) *URLWorker

func (*URLWorker) Enqueue

func (w *URLWorker) Enqueue(job *Job)

Directories

Path Synopsis
Package a2aadapter exposes Aquifer as an A2A (Agent2Agent protocol, v1.0) agent over JSON-RPC/HTTPS.
Package a2aadapter exposes Aquifer as an A2A (Agent2Agent protocol, v1.0) agent over JSON-RPC/HTTPS.
cmd
aquifer command
examples
custom_adapter command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL