---
title: "Debug a Slow API Request with API7 Gateway Debug Sessions - API7.ai"
description: "Follow one slow API request from alert to trace, separate plugin and upstream time, verify the fix, and avoid unsafe or misleading debug captures."
url: "https://api7.ai/blog/api7-gateway-debug-sessions"
---

[Blog](https://api7.ai/blog)

[Products](https://api7.ai/category/products)[Technology](https://api7.ai/category/technology)[Ecosystem](https://api7.ai/category/ecosystem)[Case Study](https://api7.ai/category/usercase)[Team & Community](https://api7.ai/category/community)

Search

⌘ + K

[Blog](https://api7.ai/blog)

Technology

# Debug a Slow API Request with API7 Gateway Debug Sessions

[![Yilia Lin](https://github.com/Yilialinn.png)](https://github.com/Yilialinn)

[Yilia Lin](https://github.com/Yilialinn)

July 26, 2026

[Technology](https://api7.ai/category/technology)

A slow API request can spend time in the client connection, gateway phases, plugins, DNS and TLS setup, or the upstream service. A latency graph shows that a problem exists; it does not show which request path consumed the time.

API7 Gateway [Debug Sessions](https://docs.api7.ai/api7-gateway/observability/debug-sessions) capture sampled HTTP requests as [OpenTelemetry traces](https://opentelemetry.io/docs/concepts/signals/traces/). A trace shows the gateway phases and plugin invocations in execution order, and current releases can attach that request's log lines to its root span. An alert policy can start the capture when its condition fires, so operators do not have to wait for a human to open a session after the event.

This runbook uses **API7 Gateway 3.10.2** as the version boundary. It shows how to capture one controlled slow request, classify the delay, apply one change, and verify the same path again. It does not claim that the example trace below was captured from your deployment.

## What You Will Prove

By the end of the investigation, you should be able to answer four questions with evidence:

1. Which gateway group, route, service, and upstream handled the slow request?
2. Which gateway phase or plugin consumed material time?
3. How much of the remaining delay belongs to the upstream or network path?
4. Did the same request shape improve after one controlled change?

The success condition is not “the trace looks faster.” It is a before-and-after pair with the same request path, a documented change, and corroborating access-log or upstream evidence.

## Prerequisites and Safety Boundaries

Prepare these inputs before creating a session:

- an API7 Gateway 3.10.2 gateway group with the affected HTTP route and service;
- permission to create and read Debug Sessions for that gateway group;
- one narrow path, host, consumer, or other sampling condition that identifies the test traffic;
- a reproducible request with secrets removed from the command history;
- access to the request's normal access log and, when needed, upstream telemetry;
- a test or low-risk production window in which a bounded capture is approved.

Debug Sessions trace HTTP traffic. They do not trace the TLS handshake or L4 stream proxying. The capture is not a packet trace, and absence of a long plugin span does not by itself prove that the upstream is slow.

Captured trace data can contain URLs, request metadata, and plugin log lines. A plugin that writes sensitive data to its log can put that data in the trace. Use the narrowest possible sample, avoid secrets in query strings, and restrict read and export permissions.

## Establish a Baseline Outside the Trace

Start with one request that represents the reported problem. Save the request start time, status, total duration, and an application-safe correlation value.

```
export TARGET_URL="https://api.example.com/checkout/preview"
export CORRELATION_ID="slow-check-001"

curl --silent --show-error --output /tmp/slow-check-body.json \
  --write-out 'status=%{http_code} total=%{time_total} connect=%{time_connect} tls=%{time_appconnect}\n' \
  -H "X-Debug-Correlation: ${CORRELATION_ID}" \
  "${TARGET_URL}"
```

Treat `X-Debug-Correlation` as a search aid, not authenticated identity. If clients can supply or preserve the header, do not use it for authorization or tenant attribution.

The curl timings cover the caller's view. They can show connection or TLS setup time, but they do not split gateway processing from upstream work. Keep them as the first channel in the evidence set.

## Create a Narrow Debug Session

In the API7 Gateway dashboard, open the affected gateway group and create a Debug Session. Set a short duration and add a sampling rule that selects only the test route or request marker your organization allows. Treat **Max Samples** as a trace-list limit, not a capture-volume limit: every request matching the rule is captured for the full duration, even after the configured number of traces has been listed. The duration and sampling rule are what bound the actual capture.

Because this runbook is pinned to 3.10.2, inspect the sampling variable before submitting the session. In versions before 3.10.5, a Dashboard preset can insert `http_uri`, `http_method`, or `http_status`. Those names read request headers and can silently match nothing. Use the built-in variables `uri`, `method`, or `status` instead. Reserve the `http_<header>` form for an actual request header.

For an intermittent production issue, attach the Debug Session configuration to the alert policy instead. API7 Gateway 3.9.13 introduced alert-triggered session creation, and the alert history records whether session creation succeeded and which session IDs were created. If a session created by the same policy remains active for the gateway group, the policy does not create another one; the active duration acts as a cooldown.

Do not broaden the sampling rule merely because the first test missed. Check these failure modes first:

- the request reached a different gateway group or route;
- the session was not active when the request arrived;
- another active session captured the request;
- the request did not satisfy the sample rule;
- the problem occurs before HTTP processing, such as during a TLS handshake;
- the traffic uses the L4 stream proxy, which Debug Sessions do not trace.

Each request is captured by at most one session. Coordinate concurrent investigations or give each session a disjoint sampling condition.

## Replay the Request and Read the Waterfall

Run the same request while the session is active. Then open its trace waterfall.

The diagram below visualizes one illustrative trace:

![An illustrative API7 Gateway 3.10.2 waterfall shows a 412 millisecond root span. Its separate children are apisix.phase.access at 380 milliseconds, apisix.phase.header\_filter at 0.25 milliseconds, and apisix.phase.body\_filter at 1.4 milliseconds. The access child contains apisix.phase.access.plugins.limit-count at 371 milliseconds.](https://static.api7.ai/uploads/2026/11/16/Ym8vDR8d_api7-debug-session-waterfall.webp?imageMogr2/format/webp)

The graphic is a simplified duration summary. Use the exact span tree when matching the example to the Debug Sessions UI:

```
GET /checkout/preview                               412 ms
├─ apisix.phase.access                             380 ms
│  ├─ http_router_match                           0.16 ms
│  ├─ apisix.phase.rewrite.plugins.key-auth        3.1 ms
│  ├─ apisix.phase.rewrite.plugins.proxy-rewrite   0.4 ms
│  └─ apisix.phase.access.plugins.limit-count      371 ms
├─ apisix.phase.header_filter                     0.25 ms
└─ apisix.phase.body_filter                        1.4 ms
```

In this example, the `limit-count` plugin is the longest instrumented child. The remaining root time is still unexplained.

The exact span names and nesting depend on the version and plugins in your route. In 3.10.2, request-side plugins—including rewrite-phase plugins—appear under `apisix.phase.access`; the phase label remains part of each plugin span name. The Debug Session waterfall does not document a separate upstream-wait span. Treat root time not explained by instrumented spans as unexplained until access-log and upstream telemetry corroborate it. Use the observed trace, not this example, as the source of truth.

Read the waterfall in this order:

1. Confirm that the root span matches the expected method, path, gateway group, and time window.
2. Find the longest child span or the largest unexplained interval.
3. Check which phase owns the long span and which plugin ran there.
4. Read the root-span log events around the same timestamp.
5. Compare the trace with the access log's gateway and upstream timing fields.
6. If the delay remains outside measured gateway work, inspect upstream application, DNS, connection, and TLS telemetry.

Plugin order matters. A route can inherit plugins from several scopes, and plugin priority determines execution order inside a phase. The trace shows the order that actually ran for that request; it is more reliable than reconstructing the order from memory.

## Classify the Delay Before Changing Anything

Use the following decision table to avoid fixing the wrong layer.

| Observation                                                  | Likely owner                                              | Next check                                                                               |
| ------------------------------------------------------------ | --------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| One plugin span dominates the trace                          | Plugin or its dependency                                  | Inspect plugin logs, dependency latency, timeouts, and the exact applied configuration   |
| Gateway spans are short; access log shows high upstream time | Upstream service or network path                          | Correlate the same request in upstream traces, DNS, connect, TLS, and application timing |
| Curl connect or TLS time is high before gateway HTTP work    | Client-to-gateway network or TLS                          | Check load balancer, DNS, certificate path, and connection reuse                         |
| Only the first request is slow                               | Connection setup, cold cache, lazy initialization, or DNS | Compare first and subsequent requests without changing the payload                       |
| One gateway instance is slow                                 | Instance-local dependency, saturation, or configuration   | Group traces by instance and compare resource and dependency signals                     |
| Successful requests are slow after a retry                   | Initial upstream attempt or retry policy                  | Count attempts and verify which target finally served the response                       |
| No trace exists for the failed request                       | Sampling, activation, protocol, or pre-HTTP failure       | Check session state and the boundary list above                                          |

The rows are hypotheses, not automatic conclusions. For example, a long `limit-count` span can reflect a Redis round trip, but the trace alone does not identify whether the delay came from Redis, DNS, network saturation, connection pooling, or the plugin itself.

## Use Per-Request Logs Without Raising Global Verbosity

API7 Gateway 3.9.15 added the request's log lines to the root trace as OpenTelemetry span events. The capture can include log messages from levels that the normal `error_log` threshold would discard. This lets an operator correlate one request's messages without switching the whole gateway to debug logging.

Treat the trace as a focused diagnostic channel, not a complete log archive. Confirm capture and truncation limits for the exact gateway release you operate before depending on the trace for complete log retention.

Before relying on a message, verify:

- which component emitted it;
- whether the value is caller-controlled;
- whether truncation removed material context;
- whether the message occurred before or after an upstream request or response;
- whether a retry or fallback created more than one upstream attempt.

## Change One Variable

Choose the smallest change supported by the evidence. Examples include:

- correct a plugin's dependency timeout or connection setting;
- move an expensive policy out of a route where it is not required;
- repair a slow Redis or external authorization dependency;
- change an upstream timeout only after confirming the upstream's expected response time;
- fix DNS or connection reuse rather than raising an application timeout;
- correct a route or service attachment that applied the wrong plugin chain.

Do not “fix” a latency incident by disabling authentication, authorization, rate limiting, or request validation without a separate risk decision. A faster request that bypasses required policy is not a successful remediation.

Record the old and new configuration revision. If the control plane accepts a change, verify that the affected data plane loaded it before starting the after-test. A saved configuration is not proof of effective runtime state.

## Verify the Same Request Path

Create a new bounded session or use the remaining approved window. Replay the same request shape, destination, identity, payload size, and connection policy.

```
export CORRELATION_ID="slow-check-002"

curl --silent --show-error --output /tmp/slow-check-body-after.json \
  --write-out 'status=%{http_code} total=%{time_total} connect=%{time_connect} tls=%{time_appconnect}\n' \
  -H "X-Debug-Correlation: ${CORRELATION_ID}" \
  "${TARGET_URL}"
```

Compare the evidence in one table:

| Channel                  | Before       | After        | Pass condition                                              |
| ------------------------ | ------------ | ------------ | ----------------------------------------------------------- |
| Caller total time        | Record value | Record value | Meets the service objective for the controlled case         |
| Gateway trace root       | Record value | Record value | Improvement is visible on the same route and instance class |
| Suspect plugin span      | Record value | Record value | Falls as predicted by the change                            |
| Upstream time            | Record value | Record value | Does not hide a new upstream regression                     |
| Status and body contract | Record value | Record value | Remains correct                                             |
| Policy decision          | Record value | Record value | Required controls still run                                 |

One request is evidence for the reproduction, not a performance benchmark. Repeat enough times for the service's normal variability, and use normal metrics to confirm that the fix holds for production traffic. Do not publish a percentage improvement without a documented sample, environment, and method.

## When Debug Sessions Are the Wrong Tool

Use another tool when the missing evidence is outside HTTP gateway execution:

- packet or TLS-handshake analysis;
- L4 stream proxying;
- client-side rendering or application code;
- model quality or semantic correctness;
- a failure that occurs entirely inside the upstream after it accepted the request;
- fleet-wide latency distributions, which belong in metrics rather than a sampled trace.

Debug Sessions answer “what did this gateway instance do for this sampled HTTP request?” Keep that boundary intact.

## Close the Investigation

A complete incident record includes the alert or reproduction timestamp, gateway group and version, sampling rule, trace ID, affected route, longest spans, correlated access-log and upstream evidence, configuration revision, after-trace, and any remaining uncertainty.

Stop or delete the session according to your incident process, but do not treat that action as trace-data deletion. Deleting a Debug Session removes the session and its trace list from the control plane; captured spans remain in Jaeger until its retention policy expires them. Trace content is stored without redaction. If sensitive data was captured, use the Jaeger deployment's own controls for removal and follow the organization's incident-data handling process rather than copying the trace into a general ticket.

The fastest path from “slow API” to a fix is not a larger dashboard. It is one bounded request, a trace that separates gateway work from upstream time, one evidence-backed change, and the same request path proving the result.

Tags:

[Observability](https://api7.ai/tags/observability)

[API Gateway](https://api7.ai/tags/api-gateway)

[Troubleshooting](https://api7.ai/tags/troubleshooting)

Share article link

Share

Related Posts

[![AISIX Observability: Metrics, Logs, Headers, and Usage Events](https://static.api7.ai/uploads/2026/07/07/UYHCYez6_2-7-7.webp)](https://api7.ai/blog/ai-gateway-observability)

## [AISIX Observability: Metrics, Logs, Headers, and Usage Events](https://api7.ai/blog/ai-gateway-observability)

[![API Gateway Multi-Tenancy: Routes Beat a Server per Endpoint](https://static.api7.ai/uploads/2026/11/24/GTCWjh37_api-gateway-multitenancy-routing.webp)](https://api7.ai/blog/api-gateway-multitenancy-routing)

## [API Gateway Multi-Tenancy: Routes Beat a Server per Endpoint](https://api7.ai/blog/api-gateway-multitenancy-routing)

Table of Contents

- [What You Will Prove](#what-you-will-prove)
- [Prerequisites and Safety Boundaries](#prerequisites-and-safety-boundaries)
- [Establish a Baseline Outside the Trace](#establish-a-baseline-outside-the-trace)
- [Create a Narrow Debug Session](#create-a-narrow-debug-session)
- [Replay the Request and Read the Waterfall](#replay-the-request-and-read-the-waterfall)
- [Classify the Delay Before Changing Anything](#classify-the-delay-before-changing-anything)
- [Use Per-Request Logs Without Raising Global Verbosity](#use-per-request-logs-without-raising-global-verbosity)
- [Change One Variable](#change-one-variable)
- [Verify the Same Request Path](#verify-the-same-request-path)
- [When Debug Sessions Are the Wrong Tool](#when-debug-sessions-are-the-wrong-tool)
- [Close the Investigation](#close-the-investigation)

## Related Posts

[![Bot Traffic Moves: Build API Defenses That Follow Behavior](https://static.api7.ai/uploads/2026/10/20/TEFXEwQQ_bot-traffic-migration-api-gateway.webp)](https://api7.ai/blog/bot-traffic-migration-api-gateway)

Technology

October 20, 2026

#### [Bot Traffic Moves: Build API Defenses That Follow Behavior](https://api7.ai/blog/bot-traffic-migration-api-gateway)

Learn why IP- and ASN-only bot controls break when automation changes providers, and build layered API gateway defenses around identity, behavior, and cost.

[API Gateway](https://api7.ai/tags/api-gateway)

[API Security](https://api7.ai/tags/api-security)

[Bot Traffic](https://api7.ai/tags/bot-traffic)

[![HTTP Connection Reuse: The Hidden API Latency Multiplier](https://static.api7.ai/uploads/2026/10/20/ChYoK0yi_http-connection-reuse-api-gateway-latency.webp)](https://api7.ai/blog/http-connection-reuse-api-gateway-latency)

Technology

October 20, 2026

#### [HTTP Connection Reuse: The Hidden API Latency Multiplier](https://api7.ai/blog/http-connection-reuse-api-gateway-latency)

Use Go 1.27's HTTP/1 change to diagnose connection reuse across clients, API gateways, and origins without hiding protocol or pool boundaries.

[API Gateway](https://api7.ai/tags/api-gateway)

[Performance](https://api7.ai/tags/performance)

[HTTP](https://api7.ai/tags/http)

[![Native Histograms for API Gateway SLOs: A Safe Migration Guide](https://static.api7.ai/uploads/2026/09/15/EUX6SgZk_native-histograms-api-gateway-slos.webp)](https://api7.ai/blog/native-histograms-api-gateway-slos)

Technology

September 15, 2026

#### [Native Histograms for API Gateway SLOs: A Safe Migration Guide](https://api7.ai/blog/native-histograms-api-gateway-slos)

Learn how Prometheus native histograms improve API latency visibility and how to migrate gateway dashboards, alerts, and SLOs safely.

[API Gateway](https://api7.ai/tags/api-gateway)

[Observability](https://api7.ai/tags/observability)

[Prometheus](https://api7.ai/tags/prometheus)
