Skip to main content

Logging under load

Every request the gateway serves produces a log record: what was asked, which model answered, how long it took and what it cost. The gateway hands that record to a background queue and answers the caller straight away, so writing the record never adds to the caller's wait. This page explains what happens when the destinations that receive those records cannot keep up, for example when a tracing backend is slow or down. In short, the gateway protects the request first. It keeps counting spend, budgets and rate limits for every request, even when the queue is completely full, and it samples the optional trace and analytics destinations to let the queue drain. Each step raises a metric, a log line and an alert so you know it happened.

A real-world scenario​

A company sends every request to a tracing backend for its data science team. One afternoon that backend starts taking two seconds to accept each trace. Without protection, the waiting records would pile up in memory and eat into the processor time the gateway needs for live requests. With this feature, the gateway's logging queue fills to 80 percent, the gateway switches to degraded mode and from then on sends only one record in ten to the tracing backend. Spend, budgets and the Admin UI Logs page still get every record. The on-call engineer receives a "Logging Overload" alert, sees spanway_logging_degraded at 1 on the dashboard, and asks the tracing team to fix their backend. Callers notice nothing, and when the queue drains below half, full logging resumes by itself.

How it works​

The gateway runs one logging queue per worker process. It has three states.

StateWhenWhat the gateway does
NormalThe queue is below the degraded mark, 80 percent of LOGGING_WORKER_MAX_QUEUE_SIZE by default.Every record goes to every configured destination.
DegradedThe queue reaches the degraded mark. It stays degraded until the queue drains to the recovery mark, 50 percent by default.Every record still goes to usage accounting and the destinations listed under "Always kept" below. Only one record in LOGGING_WORKER_DEGRADED_KEEP_ONE_IN (one in ten by default) also goes to the sampled trace and analytics destinations.
FullThe queue holds LOGGING_WORKER_MAX_QUEUE_SIZE records.A new record does not wait for room. It runs straight away beside the queue for usage accounting and the "Always kept" destinations only, and skips every sampled destination. No record is dropped, so spend, budgets, rate limits and parallel request slots stay correct.

In none of these states does the gateway make the caller wait or retry a record later. Only the full state adds background work, one short task per record that skips the sampled destinations and gives up after LOGGING_WORKER_MAX_TIME_PER_COROUTINE seconds like any other record. The gateway's separate pool for older blocking logging destinations works differently: past LOGGING_EXECUTOR_MAX_PENDING_TASKS waiting jobs it drops new ones, and those drops are counted in spanway_logging_records_dropped_total.

Always kept in degraded mode​

Spend tracking and the per request rows behind the Admin UI Logs page, budgets, rate limits and other usage counters, Prometheus metrics, the audit log, cost and billing exports, security destinations such as Levo, Azure Sentinel and Rubrik, storage archives such as S3, GCS and Azure Blob Storage, the generic API logger, alerting, OpenTelemetry version 2, MLflow, and any custom callback you wrote. These keep receiving every record, including when the queue is completely full.

Sampled in degraded mode​

OpenTelemetry version 1 and the destinations built on it (Langfuse through OpenTelemetry, Arize, Arize Phoenix, Weave and AgentOps), Datadog LLM Observability, LangSmith, Opik, Literal AI, Argilla, Braintrust, Galileo, PostHog, DeepEval and the Lens request export. In a sampled trace destination a skipped request has no model call details. With OpenTelemetry version 1 the gateway still closes the request's top level span, so the database, cache and guardrail spans recorded under it arrive with their parent instead of as broken partial traces. A custom callback class can opt in to sampling by setting the class attribute shed_when_logging_is_degraded = True, see custom callbacks. Sampling applies whatever spanway_settings.global_disable_no_log_param says, because that setting only decides whether the gateway logs its own internal calls that carry no-log.

Steps​

  1. Turn on the alert in the Admin UI. Sign in as a proxy admin, open Settings, then Logging & Alerts, then the Alerting Types tab. Find Logging Overload, read the help text under it, switch it on and click Save Changes. The page shows "Alerts updated successfully". The alert is already on when you have never chosen alert types, and it needs a Slack, Teams or webhook destination like every alert, see alerting.

  2. Or turn it on in the config file by listing it next to your other alert types:

    general_settings:
    alerting: ["slack"]
    alert_types: ["llm_exceptions", "budget_alerts", "logging_degraded"]
  3. Read the queue state from the metrics endpoint. This needs the prometheus callback, see Prometheus metrics:

    curl -s http://localhost:4000/metrics -H "Authorization: Bearer $SPANWAY_MASTER_KEY" | grep '^spanway_logging_'

    Expected result on a healthy gateway, with the counters at the totals since the process started:

    spanway_logging_queue_depth 0.0
    spanway_logging_queue_capacity 50000.0
    spanway_logging_degraded 0.0
    spanway_logging_records_dropped_total 0.0
    spanway_logging_records_sampled_out_total 0.0
    spanway_logging_degraded_episodes_total 0.0

    Each counter also prints a _created line with the time it started. The gateway refreshes these values every 10 seconds, off the request path, so they appear within 10 seconds of startup.

  4. Add an alert rule in your own monitoring if you want one besides the built-in alert, for example spanway_logging_queue_depth >= spanway_logging_queue_capacity for a full queue, or increase(spanway_logging_records_dropped_total[5m]) > 0 for jobs dropped by the pool for older blocking destinations. spanway_logging_records_sampled_out_total counts every record that skipped the sampled destinations, both in degraded mode and while the queue was full.

Settings​

These are environment variables on the gateway. Change them only when the metrics show a real need, and restart the gateway to apply them.

VariableDefaultWhat it does and when to change it
LOGGING_WORKER_MAX_QUEUE_SIZE50000How many log records each worker process may hold while destinations catch up. A bigger queue rides out longer slowdowns before records start running beside it, but every waiting record uses memory, so raise it only on gateways with memory to spare.
LOGGING_WORKER_DEGRADED_AT_PERCENT80How full the queue gets, in percent, before the gateway starts sampling. A lower value starts protecting earlier and samples more often. Allowed range 1 to 100.
LOGGING_WORKER_RECOVERED_AT_PERCENT50How far the queue must drain, in percent, before full logging resumes. Keeping it well below the degraded mark stops the gateway from flipping between the two states. Allowed range 0 to 99, and it is always held below the degraded mark.
LOGGING_WORKER_DEGRADED_KEEP_ONE_IN10In degraded mode, one record in this many still reaches the sampled destinations. 1 turns sampling off, so the sampled destinations keep every record and the queue reaches the full state sooner. A bigger number drains the queue faster but leaves fewer traces.
LOGGING_WORKER_CONCURRENCY100How many records each worker process sends at once. Raising it helps a slow but healthy destination, at the cost of more open connections.
LOGGING_WORKER_MAX_TIME_PER_COROUTINE20Seconds one record may take before the gateway gives up on it, so one stuck destination cannot hold a slot forever.
LOGGING_EXECUTOR_MAX_PENDING_TASKS10000How many jobs the pool for older blocking destinations may hold before new ones are dropped.
LOGGING_DEGRADED_ALERT_REPEAT_SECONDS600The shortest time between two "Logging Overload" alerts from the same worker process, so a long incident does not flood your channel.

The earlier variables LOGGING_WORKER_CLEAR_PERCENTAGE and LOGGING_WORKER_AGGRESSIVE_CLEAR_COOLDOWN_SECONDS are no longer read. They controlled an emergency drain that ran queued records all at once, which is exactly the burst of work this feature keeps away from live requests.

The overhead budget​

Every pull request that touches the gateway runs a benchmark in CI. A mock provider answers instantly, so what is measured is the gateway's own cost. For chat completions, streamed chat completions, Messages, streamed Messages, Responses and embeddings, the benchmark sends one request at a time through the gateway and straight to the mock, and the difference is the latency the gateway added. The pull request fails when any endpoint's added median, added 95th percentile or the gateway's own x-spanway-overhead-duration-ms timing grows past the budget in docs/data/benchmarks/overhead_budget.json, or when any request fails. A second run repeats the grid with a trace destination that takes two seconds per record and a 500 record queue. It must reach degraded mode and still stay inside the same budget, which proves that a slow logging destination does not slow requests. The full method and measured tables are on gateway overhead benchmarks.

Errors​

The gateway returns no API error for logging pressure, because callers are never affected. These are the symptoms you may see instead.

SymptomCauseFix
Traces are missing for some requests in a tracing backend, while the Admin UI Logs page has themThe gateway was in degraded mode and sampled that destination.Check spanway_logging_degraded_episodes_total and the backend's own latency. Fix the slow backend, or set LOGGING_WORKER_DEGRADED_KEEP_ONE_IN=1 if every trace matters more than headroom.
Gateway memory or open connections grow while the queue is fullEvery new record runs straight away beside the full queue, so a usage destination that is itself slow, such as an overloaded Redis, holds one task per record for up to LOGGING_WORKER_MAX_TIME_PER_COROUTINE seconds.Find the slow destination from the log lines below and fix it. Raise LOGGING_WORKER_MAX_QUEUE_SIZE if the gateway has memory to spare.
A "Logging Overload" alert arrives every ten minutesA destination is still slower than your traffic.Fix the destination, or raise LOGGING_DEGRADED_ALERT_REPEAT_SECONDS while you do.
The overhead check fails on a pull requestThe change added latency to at least one endpoint. The job summary names the endpoint and the measured value next to the budget.Find the new work on the request path and move it off, or, if the cost is intended and agreed, raise that endpoint's budget in the same pull request with the reason.

Logs​

LevelLineMeaningAction
WARNINGLoggingWorker: logging queue holds <n> of <size> records, entering degraded mode. Only 1 in <k> records goes to trace and analytics destinations until it drains below <m>A destination is falling behind and sampling started. Written once per episode.Find the slow destination. Requests are not affected.
INFOLoggingWorker: logging queue drained to <n> of <size> records, leaving degraded modeThe queue drained and full logging resumed.None.
WARNINGLoggingWorker: logging queue is full (<size> records), new log records go to usage tracking only until it drains. Requests are not slowed. Raise LOGGING_WORKER_MAX_QUEUE_SIZE or fix the slow logging destinationThe queue is full, so new records run at once for usage accounting only and skip the sampled destinations. Spend, budgets and rate limits still count them. Written once per episode.Fix the destination.
WARNINGLogging degraded: <d> log record(s) dropped and <s> sent to usage tracking only since the last check, queue at <n> of <size>. Requests are not slowedThe 10 second summary while sampling goes on. Usage tracking only covers degraded mode and the full queue, dropped covers the pool for older blocking destinations.Same as above.
WARNINGspanway logging executor backlog is full (max_pending_tasks=<n>); dropped <d> logging task(s) since the last warning. Set LOGGING_EXECUTOR_MAX_PENDING_TASKS to raise the cap.The pool for older blocking destinations is full.Fix the slow blocking destination, or raise the cap.
WARNINGLogging pressure check failed: <error>One 10 second check could not run. It is retried on the next one.None if rare.