# How to keep a redacted ring buffer of recent SDK requests

> Hold the last N requests and responses in memory, redacted as they are stored, so a failed call can be dumped with what led up to it and without a token.

Source: https://voxgig.com/howto/keep-a-redacted-debug-ring-buffer

- Audience: api-consumer
- Level: intermediate
- Languages: typescript, java, python
- Verified: 2026-11-21
- Published: 2026-11-21

## Short answer

Keep a fixed-size ring of the last N exchanges, written from the client's transport. Redact each entry before it is stored: Authorization, Cookie, and x-api-key headers, secret query parameters, and secret fields in JSON and form bodies. When a call fails, dump the ring. The same ring plugs into an openapi-fetch middleware, an OpenAPI Generator fetchApi, or sdkgen's system.fetch.

---
## You will need

Node 22.18 or later, and a client whose transport you can wrap. Java 21 and Python 3 run the other
two rings. Verified 2026-11-21 against Node 22.23.5, OpenJDK 21.0.13, Python 3.13.18,
`openapi-fetch` 0.17.0, OpenAPI Generator 7.27.0, and @voxgig/sdkgen 4.44.3. The document,
`api.json`, describes a small ledger: a login that returns a bearer token, a list of invoices, and
one invoice by id with an optional `access_token` share link. `server.ts` checks every credential
and records what it received, and every secret in it is a canary.

## Approaches compared

| Approach | When it fits | What it costs you | When to pick something else |
| --- | --- | --- | --- |
| [OkHttp HttpLoggingInterceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor) | A JVM client on OkHttp, with headers masked by `redactHeader` | A log stream, not a ring, and request and response bodies go out unmasked | You want only the calls before a failure |
| [OpenAPI Generator](https://openapi-generator.tech/docs/generators/typescript-fetch/) | Its `typescript-fetch` client, where `fetchApi` replaces the transport | No buffer of its own, and `setDebugging` in its Java `okhttp-gson` client masks no header | You want the generator to own the buffer |
| [openapi-typescript and openapi-fetch](https://openapi-ts.dev/openapi-fetch/middleware-auth) | A TypeScript client whose middleware sees every request, response, and fetch error | The body must be read from a clone in `onRequest`, and the buffer is yours to write | The client has no middleware, so wrap its fetch |
| [Python logging MemoryHandler](https://docs.python.org/3/library/logging.handlers.html) | Python code that already logs each call at DEBUG | It flushes whenever full, so every record reaches the target eventually | You want the last N records and nothing older |
| [sdkgen debug feature](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md) | An sdkgen SDK, where `debug` keeps a masked ring per client | Path templates without ids or queries, no bodies, and no `direct()` calls | You need the request body or the real URL |

Voxgig maintains sdkgen. It is one of five rows in the table, which orders them alphabetically,
not by preference.

The two logging rows cost a write on every call and need their own redaction. A ring costs memory per
client and is lost when the process crashes. `openapi-fetch` and OpenAPI Generator give you the
seam and no buffer. sdkgen gives you a buffer that records too little to reproduce a call.

## Store redacted copies in a fixed ring

The ring is an array of N slots and a write index. A push overwrites the oldest slot once the ring
is full, so memory stays at N entries however long the client lives.

```ts title="ring.ts"
  // Overwrites the oldest slot once the ring is full. O(1), no allocation.
  push(item: T) {
    this.#slots[this.#next] = item
    this.#next = (this.#next + 1) % this.#slots.length
    this.#size = Math.min(this.#size + 1, this.#slots.length)
  }
```

`DebugRecorder.record` takes the raw exchange and pushes only the redacted copy, so nothing in the
ring ever held a secret. `redact.ts` applies three rules. Headers named `authorization`,
`proxy-authorization`, `cookie`, `set-cookie`, and `x-api-key` are masked whole. A query parameter
or a JSON or form field is masked when its name contains `token`, `secret`, `password`,
`signature`, `apikey`, `credential`, or `session`. Any other body type is reduced to its length,
and every body is clipped at 200 characters. Error messages pass through a scrubber for `Bearer`
values and secret query parameters, because a transport error can quote the URL.

## Record from an openapi-fetch middleware

[`openapi-fetch` middleware](https://openapi-ts.dev/openapi-fetch/middleware-auth) gets
`onRequest`, `onResponse`, and `onError`, with the same `id` for one request. The request body is
gone by `onResponse`, so the middleware reads it from a clone first.

```ts title="adapters.ts"
  return {
    async onRequest({ request, id }) {
      pending.set(id, { started: recorder.now(), body: request.body ? await request.clone().text() : '' })
    },
    async onResponse({ request, response, id }) {
      const { started, ...rest } = base(request, id)
      const text = await response.clone().text()
      recorder.record({ ...rest, status: response.status, ms: recorder.now() - started, responseBody: text, responseType: response.headers.get('content-type') ?? '' })
    },
    onError({ request, error, id }) {
      const { started, ...rest } = base(request, id)
      recorder.record({ ...rest, status: null, ms: recorder.now() - started, error })
    },
  }
```

`onError` fires only when `fetch` itself throws. A 404 arrives through `onResponse`, which is
where the ring learns about it. `openapi-typescript` generated the `paths` types the client is
built from, and adds nothing at run time.

## Put the same ring under OpenAPI Generator and sdkgen

OpenAPI Generator's `typescript-fetch` `Configuration` takes `fetchApi`, an override for the fetch
it calls with `(url, init)`. sdkgen's generated SDK sends live requests through `system.fetch` in
the same shape. `recordingFetch` in `adapters.ts` wraps either one.

OpenAPI Generator's Java client has a debug switch of its own. In the `ApiClient.java` it wrote
for `api.json` with the default `okhttp-gson` library, read here but never compiled,
`setDebugging(true)` adds OkHttp's logging interceptor at `BODY` level and never calls
`redactHeader`:

```java title="generated/oag-java/ApiClient.java"
    public ApiClient setDebugging(boolean debugging) {
        if (debugging != this.debugging) {
            if (debugging) {
                loggingInterceptor = new HttpLoggingInterceptor();
                loggingInterceptor.setLevel(Level.BODY);
                httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build();
```

OkHttp's own [README for the interceptor](https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor)
warns that `HEADERS` and `BODY` levels can leak `Authorization` and `Cookie` headers and bodies.
Replace the client through `setHttpClient` with one whose interceptor writes to a ring.

sdkgen's `debug` feature is a ring already: `client._debug.entries`, capped at `max`, with
`authorization` and `x-api-key` masked. The demo runs it beside the hand-written ring.

## Check it worked

`demo.ts` makes four calls through each client: log in, list, load by share link, and load an
invoice that does not exist.

```bash
node demo.ts
```

```text output
openapi-fetch: the fourth call failed with status 404; the ring holds:
#1 POST /v1/sessions -> 201
   headers {"content-type":"application/json","x-api-key":"[redacted]"}
   sent {"email":"ada@example.com","password":"[redacted]"}
   got  {"token":"[redacted]"}
#2 GET /v1/invoices -> 200
   headers {"authorization":"[redacted]","x-api-key":"[redacted]"}
   got  [{"id":"inv_1","customer":"Acme","total":120}]
#3 GET /v1/invoices/inv_1?access_token=[redacted] -> 200
   headers {"authorization":"[redacted]","x-api-key":"[redacted]"}
   got  {"id":"inv_1","customer":"Acme","total":120}
#4 GET /v1/invoices/inv_9 -> 404
   headers {"authorization":"[redacted]","x-api-key":"[redacted]"}
   got  {"error":"no such invoice"}
sdkgen through system.fetch: 4 entries, last GET /v1/invoices/inv_9 -> 404
  canary secrets in the dump: none
sdkgen's own debug buffer, same calls: 3 entries
  invoice.list GET invoices -> 200, headers {"content-type":"application/json","x-api-key":"[redacted]","accept":"application/json","authorization":"[redacted]"}
  invoice.load GET invoices/{id} -> 200, headers {"content-type":"application/json","x-api-key":"[redacted]","accept":"application/json","authorization":"[redacted]"}
  invoice.load GET invoices/{id} -> 404, headers {"content-type":"application/json","x-api-key":"[redacted]","accept":"application/json","authorization":"[redacted]"}
OpenAPI Generator through fetchApi: 4 entries, last GET /v1/invoices/inv_9 -> 404
  canary secrets in the dump: none
```

The dump names the failed path, `/v1/invoices/inv_9`, and its `404`. The login and the share link
come before it, each with its secrets masked. sdkgen's own buffer missed the login, which went through `direct()`,
and records `invoices/{id}` for both loads, so it cannot say which invoice failed. The tests check
each canary against the dump and against what the server received.

```bash
node --test ring.test.ts
```

```text output
# tests 9
# suites 0
# pass 9
# fail 0
# cancelled 0
# skipped 0
# todo 0
```

## When it goes wrong

The dump shows a password. The redaction stopped at the headers, so the login body, the token in
its response, and the share link went into the ring as sent.

```bash
node pitfall.ts
```

```text output
headers redacted, URLs and bodies stored as sent
  sent {"email":"ada@example.com","password":"pw_correct-horse-battery"}
  got  {"token":"tok_live_9f8e7d6c"}
  #3 GET /v1/invoices/inv_1?access_token=share_4b3a2918 -> 200
  canary secrets in the dump: 3 of 4 (password, sessionToken, shareToken)
capacity 3, the same four calls
  the ring holds #2, #3, #4; the login, #1, was overwritten
```

Redact URLs and bodies by field name as well, before the entry is stored. The second block is the
size trade-off: a ring of three lost the call that set up the failure. Size it to the longest
sequence you would need to replay, and count the calls a retry adds.[^1]

## Build the ring from standard libraries alone

`java.net.http.HttpClient` has no interceptor chain, so `RingBuffer.java` records in the one method
every call goes through.

```bash
java RingBuffer.java
```

```text output
GET /invoices/inv_9 failed with 404; the ring holds:
#1 GET /v1/invoices -> 200 {accept=application/json, authorization=[redacted]}
#2 GET /v1/invoices/inv_1?access_token=[redacted] -> 200 {accept=application/json, authorization=[redacted]}
#3 GET /v1/invoices/inv_9 -> 404 {accept=application/json, authorization=[redacted]}
secrets in the dump: none
```

Python's `MemoryHandler` hands records over in batches rather than keeping the last N. It flushes
when its buffer fills, as well as on an error, so the target receives every record.[^2] A handler over `collections.deque` with
`maxlen` keeps the last N.

```bash
python3 ring_handler.py
```

```text output
MemoryHandler(3, flushLevel=ERROR): the target got 6 of 6 records, the first at record 3
RingHandler(3): the target got 3 of 6 records, all at record 6
  DEBUG GET /v1/invoices/inv_4 -> 200
  DEBUG GET /v1/invoices/inv_5 -> 200
  ERROR GET /v1/invoices/inv_9 -> 404
```

## When not to do this

Do not keep a ring in a short-lived process. A CLI or a serverless function that exits on the
error takes its ring with it, so write the dump in the error path or log instead.

Do not store full response bodies for large downloads. `response.clone().text()` reads the whole
body into memory once more, so record JSON and form bodies and reduce the rest to a size.

Do not rely on sdkgen's `debug` feature alone to reproduce a call. Its ring is per client and
costs nothing to switch on, but it keeps path templates, no bodies, and no `direct()` calls, so
add `system.fetch` for the gaps. Prefer `openapi-fetch` for a TypeScript consumer who wants
types from the document and nothing else at run time. OpenAPI Generator fits better when the same
document also feeds a Java or Python client that needs its own transport seam.

## Related how-tos

- [Wrap an SDK transport in a middleware chain](/howto/wrap-an-sdk-transport-with-middleware)

- [Dump requests in debug mode without leaking secrets](/howto/dump-requests-in-debug-mode-without-leaking-secrets)

- [Reduce a failing SDK call to a minimal reproduction](/howto/minimal-reproduction-of-a-failing-sdk-call)

- [Choose the layer that instruments outbound API calls](/howto/choose-a-layer-to-instrument-outbound-calls)

- [Tag SDK calls with session and request ids](/howto/tag-sdk-calls-with-session-and-request-ids)

## Last verified

Verified 2026-11-21 against Node 22.23.5, OpenJDK 21.0.13, Python 3.13.18 (and 3.12.3 for
`ring_handler.py`), @voxgig/create-sdkgen 0.31.9, @voxgig/sdkgen 4.44.3, @voxgig/apidef 8.32.4,
`openapi-typescript` 7.13.0, `openapi-fetch` 0.17.0, OpenAPI Generator 7.27.0, and TypeScript
5.9.3. Every output block is what the command preceding it printed. The generators ran once, in
`generate.sh`, and their output is committed under `generated/`. OpenAPI Generator 7.27.0's `java`
generator, with its default `okhttp-gson` library, wrote the `ApiClient.java` the page quotes. That
client was read, not compiled or run, and OkHttp was not run. @voxgig/sdkgen 4.45.0 wrote an
identical `ts/src` tree from the same project.

[^1]: The sdkgen [feature reference](https://github.com/voxgig/sdkgen/blob/main/docs/reference/features.md)
calls `debug` a request and response capture ring buffer and gives it a default `max` of 100
entries. The entry it documents carries the operation, method, URL, headers, start, status, `ok`,
duration, and error. None of the nine fields holds a body, which is why the sdkgen lines in the
demo have no `sent` and no `got`.

[^2]: The Python [logging handlers reference](https://docs.python.org/3/library/logging.handlers.html)
defines `MemoryHandler` as a `BufferingHandler` whose `shouldFlush` checks for a full buffer or a
record at the flush level. The base class documents flushing as setting the buffer to an empty
list, so a full buffer is emptied into the target rather than trimmed.