Documentation

Record & Replay Real Traffic

This is the core loop. Point the proxy at a real upstream, record live traffic in LEARN mode, run a transition to build the mock library, then flip to MOCK and serve responses from the recorded library — with no upstream connectivity required. This page walks the workflow end to end and shows how each service can run a mode of its own.

The workflow at a glance

1. LEARN

The proxy forwards every request to your upstream and records the verbatim response. Your app sees no difference — point it at the proxy and run your normal traffic.

2. TRANSITION

Recorded traffic is scrubbed and written to the mock library. The proxy enters TRANSITIONING and returns 503 + Retry-After while the write completes.

3. MOCK

Every request is matched against the library and served locally. No upstream contact. The match cascade decides how each request is answered.

Mode is persisted in data/mode.txt and watched at runtime, so a mode change propagates to the proxy without a restart. There are four modes total: LEARN, MOCK, PASSTHROUGH (forward without recording), and TRANSITIONING (the brief interstitial during a LEARN→MOCK transition).

Step 1 — point the proxy at an upstream

The proxy starts in LEARN mode by default. Set BACKEND_URL to the upstream you want to learn from — a local dev server, a staging environment, or a third-party API. Then point your application at the proxy instead of the upstream:

# Plain HTTP — point your app at the proxy on :8080
export API_BASE_URL=http://localhost:8080

# Your app's requests are forwarded to BACKEND_URL and recorded

If your app speaks HTTPS, enable the built-in TLS-MITM listener on :8443 by setting ENABLE_TLS_INTERCEPTION=true and publishing port 8443 (the supplied Compose files do not; see the TLS guide), point your client at it with HTTPS_PROXY=http://<agent>:8443, and trust the MITM CA once:

# Fetch and trust the MITM CA (served on :8080; 503 while interception is off)
curl http://localhost:8080/ca.crt > gostly-ca.crt
# then add gostly-ca.crt to your client / OS trust store

Protocols recorded

Gostly records and replays HTTP and HTTPS — HTTP/1.1 and HTTP/2 over TLS. WebSocket frames are captured for observability only and are not replayed; there is no gRPC, async-messaging, or database mocking yet (roadmap).

ENABLE_TLS_INTERCEPTION is tri-state: default off; true/lax (a listener failure logs and keeps plain HTTP serving); strict (a TLS failure exits the process — you've declared TLS load-bearing). Outbound fingerprint impersonation (genuine Chrome / Firefox / Safari TLS fingerprints) is layered on top of this, opt-in per service.

See Proxy Setup for the per-OS trust-install steps and the Caddy-fronted TLS alternative.

Step 2 — record in LEARN mode

In LEARN mode the proxy is a transparent pass-through. Every inbound request is forwarded to the upstream; the response is returned to the caller and recorded. Generate traffic the way you normally would — run your test suite, click through the app, or replay a capture. There is no minimum; even a handful of interactions is enough to start replacing upstream calls. In LEARN and PASSTHROUGH modes, a response that declares its length is read in full before it is returned, up to 32 MiB by default; a larger response gets a 502 from the proxy and is not recorded. To raise the limit, set MAX_RESPONSE_BODY_BYTES to a byte count in the ghost-proxy service's environment. The shipped Compose file does not pass it through from .env, so add it in a Compose override file. The value must be a plain integer number of bytes, such as 67108864 for 64 MiB. A value with a unit or separators, such as 64MiB, is ignored, the proxy logs a warning, and the 32 MiB default stays in force.

A streamed response is passed to the caller as it arrives, with no size limit. That covers server-sent events (text/event-stream), a chunked transfer, and a compressed response. LEARN records a streamed response only when it ends within 1 MiB and 60 seconds. Set MAX_BODY_BYTES (bytes) and MAX_STREAM_CAPTURE_SECONDS the same way as MAX_RESPONSE_BODY_BYTES to change those bounds. A stream that passes either bound, or whose caller disconnects first, is recorded as partial. MOCK answers a partial recording with a 422 error and never replays it as a complete response. If the upstream breaks a stream partway, the caller's response is cut off too. Nothing is recorded for that response unless a bound had already closed the capture; in that case the partial recording made at the bound remains, and MOCK still refuses it.

Recording fans out to three independent sinks, each with its own redaction posture:

In-memory verbatim

The active LEARN session is held verbatim in RAM (bodies and headers) so it can replay verbatim while the window is still open. This buffer never touches disk and never leaves the box; it resets on restart or a new LEARN window.

Disk JSONL

Recorded interactions are written to per-service JSONL in the shared gostly-data volume. Credential headers are stripped here by default before anything is written — this is the redaction floor.

Shipped

Telemetry and wide-event streams that leave the host are always redacted, with no opt-out. Exports from the mock library are scrubbed by default; an export can explicitly include unscrubbed rows.

What gets redacted, and when

A fixed 16-header credential floor (Authorization, Cookie, Set-Cookie, API-key headers, session and CSRF tokens, cloud session tokens, and similar) is stripped by default before anything is written to disk. The REDACT_HEADERS env var and per-service rules can only add to this floor — they cannot shrink it. Keeping recorded headers on disk takes an explicit air-gap opt-out.

PII in request/response bodies is kept verbatim on your local replay library (so structural and value-matching tests stay production-accurate) and is scrubbed from recorded traffic when it is promoted into the Postgres store and in default exports. Snapshot imports pass through the same scrubber on their way into the Postgres store. Imported and seeded mocks receive structural credential redaction and a sensitive response-header floor before storage. These rules do not cover all personal data; review and sanitize source files before uploading.

You can check what's been captured from the dashboard at localhost:3000 or via the control-plane API on port 8000.

Step 3 — transition to build the library

In the dashboard, open the service and choose Build mocks on its Overview, or choose Process for the service on the Traffic page. Both start this transition, which builds the library and switches the service to MOCK. To record more for that service afterward, switch it back to LEARN with the mode control on the right of the header on the service's Overview. The control shows the service's current mode, and its menu lists Learn, Mock and Passthrough. A choice is saved at once and applies to that service only. The Default mode on the Services page is a separate control: it sets the mode for services that have no mode of their own.

When you trigger a transition, the API reads the recorded traffic, runs it through the scrub pipeline, and persists the result. During the write the proxy enters TRANSITIONING and returns 503 Service Unavailable with a Retry-After header — this is intentional, and prevents partial-library matches mid-write. Once the API signals completion, the proxy reloads the per-service mock library and is ready to serve.

Flip directly, or transition first

The transition step is what scrubs traffic into the durable Postgres store. You can also flip a service straight to MOCK — the active LEARN session already replays verbatim from memory — but a transition is what produces the committed, reloadable library that survives a restart and is what CI mounts.

Step 4 — flip to MOCK and replay

Switch to MOCK mode from the dashboard or via the API. The shipped compose runs the control plane fail-closed, so every control call on port 8000, except the two health endpoints, carries the X-API-Key header. Its value is the GHOST_API_KEY generated in your .env by ./setup.sh; admins can also copy it from Settings in the dashboard. Load it into your shell from the install directory first:

# Load the key from .env (run in the directory holding .env)
export GHOST_API_KEY="$(grep '^GHOST_API_KEY=' .env | cut -d= -f2- | tr -d "'\"")"
: "${GHOST_API_KEY:?No GHOST_API_KEY in .env, copy the key from Settings in the dashboard}"

# Flip the global mode to MOCK
curl -X POST http://localhost:8000/v1/mode \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"mode": "MOCK"}'

Your app keeps talking to http://localhost:8080. Each inbound request now runs through the match cascade below. The order is fixed: cheaper, more-deterministic tiers run first, and a generated response answers the caller only when nothing earlier matched. Model work can still run in the background, for example after a smart-swap answer or a cache miss (see Match Cascade).

Session verbatim

Deterministic

If the request was seen during the active LEARN session, the in-memory capture replays it verbatim from RAM — bodies and headers — and stamps X-Ghost-Mock: session-verbatim. RAM-only; never leaves the box.

Exact match

Deterministic

Method + URI + request body match a recorded entry exactly. An O(1) lookup against the disk-loaded library; stamps X-Ghost-Mock.

Resource store

Deterministic

Links a resource created earlier in the session to a later read — a POST that creates a resource lets a subsequent GET-by-id return it instead of a 404.

Statechart transition

Deterministic¹

A Harel statechart models resource lifecycles, so PATCH /collection/{id} {"action":"X"} (or POST /collection/{id}/{action}) advances state and rewrites the status field, tagging the response X-Ghost-Transition.

Smart swap

Deterministic

URI path parameters are normalised to templates (/users/{id}) and matched structurally — a recording of /users/42 serves a request to /users/99.

AI generation (cached)

When AI is enabled

Last resort. With no earlier match, a generated response is served from cache. With AI off, the cascade stops at smart swap.

¹ The statechart engine runs in every installation. Its five bundled lifecycles (charge, customer, invoice, order, subscription) are off by default, and a workspace can turn them on from the dashboard Statecharts page.

No LLM in the request hot path — ever

This ordering is an architectural invariant, not a tuning default. AI generation never runs synchronously inside a request: generation is dispatched to a background worker behind a bounded queue, and the request is answered from cache. A regulated or latency-sensitive deployment can disable generation entirely and the stack runs fully deterministically through smart swap.

Recorded timing

A response replayed from your recorded traffic waits as long as the original upstream response took (up to a cap), so your app sees realistic timing. Each service controls this:

  • Replay (default) — wait for the recorded time, up to a cap. The default cap is 10 seconds; set it anywhere from 1 ms to 60 seconds.
  • Don't replay — serve recorded responses immediately, for fast test runs.

Change it in the service's settings in the dashboard, or with the API (each update replaces the whole setting):

curl -X PUT http://localhost:8000/v1/services/{service_id} \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"recorded_latency": {"mode": "replay", "cap_ms": 2000}}'

Send {"mode": "none"} to stop replaying recorded timing, or {} to restore the default. Only answers replayed from your recorded traffic (session-verbatim, exact and smart-swap matches) wait. Every other answer, including resource-store and statechart answers and every AI-tier answer (even one that reuses a close recording), adds no recorded delay. Chaos latency is separate and adds on top when chaos is enabled.

Per-service modes

A single proxy instance handles many upstreams at once, and each service carries its own mock library, mode, chaos config, and redaction rules. That means one service can stay in LEARN while another already replays in MOCK — useful when you're recording a new dependency without disturbing the ones you've already locked down:

# Switch one service to MOCK while the others keep recording
curl -X PUT http://localhost:8000/v1/services/{service_id} \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"mode": "MOCK"}'

# Or set the global mode. A service that has its own mode keeps it.
curl -X POST http://localhost:8000/v1/mode \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"mode": "MOCK"}'

See Multiple upstream services for host-based and path-based routing. Each deployment is single-tenant, with its workspace identity set through GOSTLY_TENANT_ID. Application queries remain tenant-scoped, and Postgres enforces RLS beneath them through the non-owner API request role, transaction-bound tenant context and FORCE ROW LEVEL SECURITY on covered tables. Cross-tenant maintenance uses a separate privileged role. See the security model.

Seeding without live traffic

If you can't (or don't want to) record live traffic first, seed the library from artifacts you already have. Drag a HAR export, Postman collection, or OpenAPI spec onto the dashboard, which posts it to the corresponding importer:

# Cold-start import — one endpoint per format
curl -X POST 'http://localhost:8000/v1/seed/har?service_id=svc-payments' \
  -H "X-API-Key: $GHOST_API_KEY" \
  -H 'Content-Type: application/json' \
  --data-binary @recording.har

# Also: /v1/seed/postman and /v1/seed/openapi

A seeded service replays through the same cascade as a recorded one — you can start in MOCK with a seeded library and add live recordings later.

Watching for drift

A replayed library is only as good as it is current. When recorded responses diverge from what the live upstream now returns, Gostly emits drift events and surfaces a freshness score (0–100) with a sparkline trend per service, so you can see at a glance which mocks are going stale.

The AI mock-repair surface can turn a drift event into a proposed fix that an operator approves or rejects. The auto-proposer loop is off by default (enable with ENABLE_AI_MOCK_REPAIR=true); manual approve / reject works either way — Gostly never rewrites a mock without an operator in the loop.

Observing what the proxy did

Every served request increments a Prometheus counter labelled by how it was answered, so you can verify the cascade is doing what you expect. The agent exposes these on /metrics:

ghost_requests_total{match_type="..."}   # one of: session_verbatim, exact,
                                          #   resource_store, resource_transition,
                                          #   smart_swap, generated_cached, miss,
                                          #   learn, transitioning, passthrough, chaos
ghost_mock_library_size                   # mocks currently loaded
ghost_io_errors_total{operation="..."}    # disk-sink failures
axum_http_requests_total                  # HTTP rate
axum_http_requests_duration_seconds       # HTTP latency
# gostly_tls_* family covers the TLS-MITM subsystem

Inspect one response as well as aggregate metrics. For a routed request outside a deterministic episode, X-Gostly-Behavior identifies the selected service and response source. Server-Timing separates source processing, recorded latency and injected latency. These headers are enabled by default; service configuration can suppress them. Deterministic episodes use their journal for attribution instead.

A source marker identifies the layer that chose the response. It does not prove the entry came from upstream capture or that your application handled it correctly. See Provenance headers for members, exceptions and the X-Ghost-* tier markers.

Licensed product vs. the OSS proxy

The workflow above describes the licensed Gostly product, which ships as docker-compose plus container images — there is no host CLI to install; you drive everything through the dashboard and the control-plane API. The OSS proxy is a separate product distributed via Homebrew and a container registry, and it does ship a host CLI. The two share the record-and-replay concept; the tiered AI cascade, drift, statechart overrides, and the team features described here belong to the licensed product.

Worked procedures

Apply the record-and-replay workflow to a client regression or a controlled agent comparison. The first is an authored local consumer example; the second keeps API conditions steady while your own evaluation harness judges agent behavior.

Reproduce a client bug →

Download the synthetic order-response packet, compare the broken and corrected client checks, and carry the same assertion into your own replay workflow.

Markdown version
Compare agent versions →

Give two agent versions the same reviewed HTTP conditions, reset the task state, and keep external evaluation scores separate from Gostly evidence.

Markdown version

Next steps