●CODE 2.1.319 — Claude Code now moves MCP tasks to the background automatically, and a denyInsteadOfPrompting setting denies calls that would wait on a prompt●FABLE 5.2 — Claude Fable 5.2 and its fast mode are on the Claude API (11/9). Mythos 5.2 is limited to verified organizations●SONNET 4.5 — Retires on the Claude API on 11/30, 20 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST — Opus 4.8 fast mode is deprecated and will be removed on 11/30. Migrate to Opus 5.5●NEW — I Put a Ten-Line Promise File at the To…●CODE 2.1.319 — Claude Code now moves MCP tasks to the background automatically, and a denyInsteadOfPrompting setting denies calls that would wait on a prompt●FABLE 5.2 — Claude Fable 5.2 and its fast mode are on the Claude API (11/9). Mythos 5.2 is limited to verified organizations●SONNET 4.5 — Retires on the Claude API on 11/30, 20 days left. Migrate to Sonnet 5.5●WINDOWS — Reports say hooks break silently only on Japanese-locale Windows; check the character encoding first●FAST — Opus 4.8 fast mode is deprecated and will be removed on 11/30. Migrate to Opus 5.5●NEW — I Put a Ten-Line Promise File at the To…
Archiving Claude API Responses to Cloudflare R2: An Implementation Memo for Audit, Replay, and Incident Analysis
An implementation memo on persisting Claude API requests and responses into Cloudflare R2 so you can audit, replay, and triage production incidents — covering Workers waitUntil patterns, PII masking, and a D1 metadata index for fast lookups.
Anyone running Claude API in production eventually hits the moment when they wish they could see "that one response from last week." A user emails to say last Tuesday's output was off; a wave of 429s rolled through your system at 02:00 and you want to know what was actually being asked; you suspect a prompt regression and want to compare yesterday's outputs against today's. In my case the trigger was an AdMob eCPM monitoring bot that returned strange output one morning. With only fragments of console.log in hand, I spent the whole day trying to guess my way back to a reproduction.
Since then I have run a simple rule: every Claude API request and response gets archived to Cloudflare R2. The same design runs behind the backends of my own apps and sites. What follows is the implementation memo — short enough that, by the end, you should be able to add archiveResponse(...) to your own Worker in about five lines.
Why Archive Claude API Responses at All — Three Operational Needs
Before any code, it helps to be honest about what the archive is for. Pulling everything into storage without a purpose just produces an expensive graveyard. I only write to R2 when at least one of three concrete needs is at stake.
Audit. When a generative model is sitting behind a paid feature, you will eventually need to demonstrate, after the fact, what the model actually said — not what you edited it to say. In one of my apps the user-review reply feature was accused of "writing something factually wrong"; being able to show the original response cleared up the misunderstanding immediately. Later analyses of how often stop_reason came back as refusal are also impossible without the raw response in hand.
Replay. With prompt caching enabled, you'll want to study cache hit rates and the effect of system-prompt diffs on output. If both the input and the output were archived, you can assemble a golden dataset retroactively. I build a regression suite from those archived responses to track quality drift across model switches — for example, Sonnet 4.6 against Opus 4.6 — and without the archive there would be nothing to compare against.
Incident analysis. Distinguishing real-time alerts from postmortem material matters here. Alerting belongs in observability tooling. But once you sit down to root-cause a problem — the time-of-day skew of 529 Overloaded errors, the distribution of max_tokens cutoffs, the pattern of streaming disconnects — having the full text of what was sent and received in front of you cuts investigation time by an order of magnitude.
If even one of those three matches your project, archiving earns its keep. If none feel relevant right now, you can wait. There is no virtue in collecting data you have no use for.
Designing the Data Model: Key Strategy and Partition Granularity
R2 is object storage; there is no real directory concept, only a flat keyspace. Design that key naming carelessly and you'll find yourself LIST-ing the entire bucket to pull out "all responses for user X last Tuesday." The naming convention I run with is:
So claude-archive/2026/05/24/02/req_01HXYZ.json is a typical object. Partitioning by hour rather than by day is a deliberate choice tied to R2's LIST behaviour and to the lifecycle rules below. R2 returns up to 1000 objects per LIST call. At a million requests per month, an hour-bucket averages about 1400 objects, comfortably within range; a day-bucket would hold ~33,000 and require multiple paginated LIST calls for even casual exploration.
The request-id is the value of the Anthropic response header of that name. (The msg_... ID in the body is a different thing; the sample code uses response.id for simplicity, but if you want to match what support quotes back to you, store the header value in customMetadata too.) Reusing it as the key means that when a user emails with req_01HXYZ... in hand, you can pull the object directly given the year-month-day-hour. When the request-id is missing, you fall back to the D1 metadata index described later.
Each object holds the request and response together as JSON:
Including schema_version from day one is the single most important habit. You will, almost certainly, want to add a field later — I added cache_read_input_tokens to v2 months after the initial design — and the version tag lets the replay code branch cleanly on shape. I learned this the painful way: not including it, then having to write a four-month-deep heuristic to guess at older records' structure.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦A Workers pattern that archives every Claude API response to R2 asynchronously, adding almost no latency to the hot path
✦A D1 metadata index design that turns a single request-id into a one-query lookup during an incident
✦Realistic R2 cost math for a 1M-request-per-month workload, including Class A operations and lifecycle rules
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Writing to R2 from Cloudflare Workers Without Slowing the Hot Path
To avoid lengthening the user-facing latency, every R2 write runs through ctx.waitUntil. That keeps the Worker alive past the moment the HTTP response is returned so the side-effect can finish in the background.
Here's the bare version of a Worker that returns Claude's response and does nothing else:
A subtlety worth understanding: when a Promise inside waitUntil rejects, you'll see the exception in the Workers Logs, but the user-facing response has already gone out. So a partial archive is possible (R2 wrote successfully, D1 failed). I fix the order at "R2 first, then D1" and route D1 failures to a dead-letter Queue keyed by request_id. Having a batch-fixup path is a low-effort insurance policy that pays off after the first quarter of running this in production.
For streaming (anthropic.messages.stream(...)) the archive call moves to after finalMessage() resolves. If the SSE connection drops mid-stream, write what you have with a stream-truncated flag so you can isolate that failure mode in later analyses.
PII Masking: Don't Persist What You Shouldn't Persist
If you intend to keep this archive as an audit log, you have to be deliberate about PII. Consumer-facing apps in particular tend to receive user input with raw email addresses, phone numbers, or even physical addresses inside the prompt. In my wallpaper app, the review-reply assistant sometimes received review text with home addresses embedded; I had to think hard about whether to persist that at all.
Before writing to R2 I run maskPII() over the request:
The critical mindset here is don't try to be perfect. Perfect PII detection is effectively impossible, and chasing it tends to start eating into the content you actually want to keep. My rule is:
Mechanically mask things that have structure (emails, phones, card numbers, tokens)
For unstructured PII (free-form addresses, names inside prose) shorten the retention window instead of masking
For request flows that involve regulated data (age verification, health-related), set an archive_policy: "skip" flag and never archive at all
That last flag is something I keep on the Worker side, separate from Anthropic's metadata.user_id. If archive_policy === "skip", the Worker doesn't even call archiveResponse.
Replaying an Incident: From a request-id Back to a Reproduction
A concrete walkthrough of how this paid off. One morning I was chasing a wave of intermittent 529s tied to a Cloudflare Queues integration. The dashboard only told me "error rate spiked at this minute." Pulling out what was actually being requested at that minute was where R2 came in.
# 1. Pull requests cut off by max_tokens from D1 by time windowwrangler d1 execute my-archive-db \ --command "SELECT request_id, r2_key FROM archive_index WHERE ts BETWEEN '2026-05-24T02:00:00Z' AND '2026-05-24T02:30:00Z' AND stop_reason = 'max_tokens'" \ --remote --json | jq -r ".result[0].results[] | .r2_key" > keys.txt# 2. Fetch each archived objectwhile read key; do wrangler r2 object get "my-archive-bucket/${key}" \ --file "./pulled/$(basename $key)"done < keys.txt# 3. Feed them through a replay scriptnode tools/replay.mjs ./pulled
The replay script reads each JSON, re-sends the request portion, and compares behaviour:
What the replay actually told me was that 529s did not reproduce — they were transient backend overload, not a function of the request content.
To be honest, my first version only archived successful responses, so for that very 529 investigation the failing side was missing. I added a write to the catch block the next day. The failure record can be this light:
// Archive the failure side in the same shape (call this from the catch block)async function archiveFailure(args: { env: Env; request: ChatRequest; error: unknown;}) { const { env, request, error } = args; const now = new Date(); const status = (error as { status?: number }).status ?? 0; const id = crypto.randomUUID(); const key = `claude-archive-errors/${now.toISOString().slice(0, 13).replace(/[-T]/g, "/")}/${id}.json`; await env.ARCHIVE_BUCKET.put( key, JSON.stringify({ schema_version: "v1", ts: now.toISOString(), status, message: error instanceof Error ? error.message : String(error), request: maskPII(request), }), { httpMetadata: { contentType: "application/json" } }, );}
Keeping a separate key prefix from the success side lets you LIST just the incident window. An archive that only keeps successes is empty on the day you need it most. By contrast, stop_reason: "max_tokens" cases reliably reproduced as cutoffs, which led me to raise the limit or add a "respond in N characters" constraint in the system prompt. Being able to separate "reproducible incidents" from "transient ones" was the real win. That separation is impossible without an archive.
A D1 Metadata Index for Fast Lookups
Relying on R2 alone forces every search through LIST, which is a Class A operation and pricey at scale. I keep a small D1 table as the search layer:
CREATE TABLE archive_index ( request_id TEXT PRIMARY KEY, user_id TEXT NOT NULL, ts TEXT NOT NULL, model TEXT NOT NULL, stop_reason TEXT, input_tokens INTEGER, output_tokens INTEGER, r2_key TEXT NOT NULL);CREATE INDEX idx_archive_user_ts ON archive_index (user_id, ts);CREATE INDEX idx_archive_ts_stop ON archive_index (ts, stop_reason);CREATE INDEX idx_archive_model_ts ON archive_index (model, ts);
D1 is inexpensive but not free. I age out rows older than 90 days into a archive_index_history table keyed on r2_key only, so the hot index stays small. D1 becomes the recent and fast index; R2 stays the long-term truth.
Three search patterns cover almost everything you'll do:
A user sends a request-id to support — WHERE request_id = ?
All recent requests for a user — WHERE user_id = ? AND ts > ?
Distribution analytics like "max_tokens cutoff rate by model" — WHERE model = ? AND stop_reason = 'max_tokens' over a window
For analytics queries you'll outgrow D1 eventually and want a periodic export into Workers Analytics Engine or Snowflake. Most indie projects and small SaaS apps never reach that point — D1 is enough.
R2 Cost Math: Class A Operations and Storage
"Archive everything, it's cheap" is half true. R2 has three billing axes and Class A operations (PUT / LIST / DELETE) start to dominate at scale.
Working with R2's general-region pricing as of May 2026 and assuming a million Claude API requests per month:
Storage: an 8 KB average response × 1M = 8 GB/month, at roughly 0.015 USD/GB → about 0.12 USD/month. Effectively free
Class A (writes): 1M PUTs at roughly 4.50 USD per million → about 4.5 USD/month. This is the dominant cost
Class B (reads): occasional incident-analysis fetches in the low thousands → noise; even 10K GETs/month at roughly 0.36 USD per million is well under a cent
That's around 5 USD/month for the whole picture, D1 included. Cheap relative to app ad revenue, but easy to blow past if you LIST aggressively. The classic mistake is "scan the past week of responses for analytics" run daily — that's 168 hour-buckets × multiple LIST calls per bucket per day, and Class A balloons. I first built that scan on R2 LIST alone, and the month-end bill showed Class A at several times what I'd expected. The fault was my batch design, not R2. Since then I funnel all analytics through the D1 index. R2 is the retrieve known keys store, D1 is the discover keys store.
The other lever is lifecycle rules: move objects older than 30 days to Infrequent Access, delete past 90 days, configured via wrangler r2 bucket lifecycle add .... Infrequent Access storage is roughly two thirds of standard pricing, but it adds a data-retrieval fee, higher per-operation rates and a 30-day minimum storage duration. For objects you rarely read the total drops; if your incident analysis pulls them in bulk, it can flip. Prices change, so check the official pricing page before you commit.
Lessons From Actually Running This for Six Months
A few rough edges that only revealed themselves once the design met traffic:
First, when a key you just wrote seems to be missing, suspect your own ordering before R2's consistency. R2 is designed to give strong read-after-write and LIST consistency. I still managed to double-PUT once, because an existence check ran on a different path while the waitUntil PUT hadn't finished. The fault was mine, not R2's. I now accept the duplicate (same JSON, idempotent overwrite) and put any existence check after the await.
Second, streaming and client disconnects. If a user closes the tab during messages.stream(), the Worker may exit before finalMessage() resolves. The fix is to consume the stream with for await (const event of stream) and trigger waitUntil(archive(...)) explicitly on event.type === "message_stop". That way the archive write fires even if the HTTP client is long gone.
Third, the prompt cache contents are not part of the archive. The API returns cache_read_input_tokens so you can see how much was reused, but not what was reused. I record the ratio usage.cache_read_input_tokens / usage.input_tokens in D1 as a trend signal and let go of the dream of bit-perfect replays.
Keep what you can reproduce as fact, and treat what you can't as a trend. When I chased perfect replays, the verification code grew larger than the feature it was checking.
If you're starting from a stock Worker, the smallest meaningful step is to wire archiveResponse(...) into ctx.waitUntil and confirm a day's worth of objects shows up in your R2 bucket. The D1 metadata index can be added later — every record still has a key, so you can backfill from R2 if needed.
For the first six months I ran R2 only, pulling support tickets one object at a time with wrangler r2 object get. Adding the D1 index cut support response times by something like 5×. An archive worked better for me as a grow it as you need it habit than as a perfect design up front. Add the five lines today, and check tomorrow morning that the first object landed in your bucket. I keep to that order even on days when the design isn't settled.
Share
Thank You for Reading
Claude Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.