Skip to content

Spike: HTTP cache headers for immutable API responses #128818

Open

Description

@sentry-junior

Most API GET responses send no cache validators or freshness headers, so browsers and API clients cannot reuse responses, even for data that never changes after it is written, such as events and traces. The Sentry CLI works around this with client-side TTL tiers, and other clients get no caching at all.

Background

  • src/sentry/api/conditional_get.py (ConditionalGetResponseMixin, feat(seer): Support conditional requests on the autofix state endpoint #121885) already adds an ETag, Cache-Control: private, no-cache and Vary: Cookie, Authorization, and answers If-None-Match with a 304. It is gated by the api.conditional_get.enabled option, and only the autofix state endpoint uses it.
  • The CLI's fallback TTL tiers (packages/cli/src/lib/response-cache.ts in getsentry/toolkit) treat event and trace lookups as immutable (24h), and organization, project and team data as stable (5m).

Proposal (from the requester)

Send Cache-Control: private, immutable (with a max-age) on never-changing results, with Vary headers that keep cached responses scoped to a session or credential. If that is not feasible or not enough, revisit client-side caching in the frontend.

Scope of the spike

  • Which endpoints return immutable data, and which edge cases break that (for example deleted data, data scrubbing, retention expiry, permission changes).
  • Whether Vary: Cookie, Authorization is enough to keep caches scoped to one session or token, including in the browser and behind proxies.
  • Whether ConditionalGetResponseMixin can be the base for this, and what hashing a full response body costs on large endpoints.
  • How the browser cache would interact with the frontend's existing request layer.

via BYK.

--

View Junior Session in Sentry

Activity

  1. linear-code commented on Oct 26, 2026

    @linear-code
  2. sentry-junior commented on Oct 26, 2026

    @sentry-junior
    ContributorAuthor

    Spike findings

    Short answer: immutable is not safe for any of the candidate endpoints. Each one embeds or depends on state that can still change under the same URL. A bounded Cache-Control: private, max-age=N (start with N = 300) is feasible for organization event details and trace-item details. It is not feasible for the trace endpoint or for project/group event details. Draft prototype: #128828. It is behind a new option that defaults to off.

    Line references are at 06a3bc41dda (master when the spike ran).

    1. Candidate endpoints

    Endpoint Verdict What still changes the response
    organizations/{org}/events/{project}:{id}/ (OrganizationEventDetailsEndpoint) max-age OK release comes from the live Release row (api/serializers/models/event.py:487-504). groupID and occurrence (event.py:345,367) change on merge, unmerge, and reprocessing. projectSlug changes on a project rename (issues/endpoints/organization_event_details.py:154). ?averageColumn= adds live 24h span averages (organization_event_details.py:30-78,139-145), so it must not be cached.
    projects/{org}/{project}/trace-items/{id}/ (ProjectTraceItemDetailsEndpoint) max-age OK Output differs for active superuser and staff sessions (api/endpoints/project_trace_item_details.py:525) and for superusers passing ?debug (:468). A feature flag adds array fields (:519), so a flag rollout changes the response for the same URL. Otherwise the EAP item does not change once written.
    projects/{org}/{project}/events/{id}/ (ProjectEventDetailsEndpoint) no nextEventID and previousEventID are computed from the group's current events (issues/endpoints/project_event_details.py:67-101), so the newest event's "next" link changes as events arrive. It also embeds userReport, which is added after ingestion (event.py:261-268,577), and sdkUpdates, which reflects the current SDK index (event.py:554-555).
    issues/{id}/events/{id}/ (GroupEventDetailsEndpoint) no Same as above, plus the latest, oldest, and recommended aliases (api/urls.py:947).
    organizations/{org}/trace/{trace_id}/ (OrganizationTraceEndpoint) no Late spans and errors keep arriving. culprit and short_id are read live from Group (snuba/trace.py:160-213). Results are filtered to the projects the caller can access (api/endpoints/organization_trace.py:77-97). A relative statsPeriod slides over time. At most use no-cache plus an ETag.
    projects/{org}/{project}/events/{id}/json/ (EventJsonEndpoint) max-age OK, low value Raw payload, but IP scrubbing is applied at read time from a project option (project_event_details.py:204-219).

    Cross-cutting breakers, all of which apply to the "OK" rows:

    • Reprocessing re-inserts events under the same event ID with new symbolication and a new group (reprocessing2.py:20-27,83). Merge moves events to another group (tasks/merge.py:92). Both change the response at the same URL.
    • Deletion and retention expiry: the cached copy outlives the data by up to max-age.
    • Data scrubbing is not a breaker. Advanced data scrubbing runs before the event is saved and is not applied to stored events. The exception is the read-time IP scrubbing in EventJsonEndpoint above.
    • Permission changes and member removal: the session cookie does not change, so Vary does not help. A removed member keeps cached responses for up to max-age. This, plus the GDPR deletion story, is the main reason to keep N small.
    • Query params: every param is part of the cache key, so varying params are safe by construction. Only params that pull in live data, such as averageColumn, need to opt out.

    2. Scoping

    • No API Cache-Control today. Apart from ConditionalGetResponseMixin, nothing in src/sentry/api/ or src/sentry/middleware/ sets Cache-Control. The only other Cache-Control code is for static assets (web/frontend/base.py:890). getsentry only uses never_cache on two identity views. API responses already get Vary: Cookie from Django's SessionMiddleware (conf/server.py:391) whenever the session is accessed. They get Vary: Accept-Language from SentryLocaleMiddleware (middleware/locale.py:14-20).
    • Nothing strips the headers. The control-silo API gateway copies all non-hop-by-hop response headers through (hybridcloud/apigateway/proxy.py:98-100).
    • Logout, or login as another user: sessions use signed cookies (conf/server.py:686-687), so any change to the session rewrites sentrysid and changes the Cookie header. The cached entry stops matching. Superuser "view as" stores login_as in the session (getsentry vendor/viewas/middleware.py), so the same applies.
    • Superuser and staff: the su cookie is re-signed on every response while active (auth/superuser.py:562-575). That gives a near-zero hit rate, which is harmless. The risk is an expired or IP-restricted superuser session replaying a cached privileged response before the cookie changes. Recommendation: never send max-age for active superuser or staff sessions. The prototype does this.
    • Org switching: the org is in the path or the subdomain, so each org has its own URL and its own cache entry. No leak.
    • Gap: Origin is missing from Vary. API responses reflect the request origin in Access-Control-Allow-Origin and allow credentials (api/base.py:207-220, applied at :541). The frontend calls the region host cross-origin (static/app/utils/api/resolveHostname.ts:20-24). With no-cache, revalidation refreshes ACAO. With max-age, a response fetched from sentry.io and reused from <org>.sentry.io fails CORS. max-age responses must add Vary: Origin.
    • Hit-rate caveat (inference, not measured): Vary: Cookie keys on the whole Cookie header. JS-written analytics cookies and session rewrites change it, which forces a miss. That is safe but lowers the hit rate. The existing api.conditional_get{result=hit|miss} metric on autofix polling measures how often the browser's Vary matches. Check it before choosing N.
    • CDNs and proxies: use private, never public. Many CDNs ignore Vary: Cookie. private forbids storage in compliant shared caches. I could not verify from the repo which CDN or proxy sits in front of the API.

    3. Mechanism

    Extend ConditionalGetResponseMixin rather than add a sibling. The 200/GET/HEAD gating, in-place 304, and metrics are all reusable. Prototype in #128828:

    • cache_max_age class attribute, plus uncacheable_query_params for live-data params.
    • It only applies when the endpoint class name is listed in the new api.conditional_get.max_age_endpoints option, and the existing api.conditional_get.enabled acts as the global kill switch.
    • When active it sends private, max-age=N and Vary: Cookie, Authorization, Origin. Superuser and staff sessions fall back to no-cache.
    • Keep the ETag. After the max-age runs out, the browser revalidates and gets a 304 instead of the full body.
    • Hashing cost: blake2b measured about 0.66 GB/s in the sandbox (≈1.5 ms per MB, 15 ms per 10 MB). That is small next to the nodestore and Snuba reads behind these endpoints. render() was going to run anyway; the mixin only runs it earlier. For reference, orjson rendered a 0.84 MB payload in 1.3 ms.
    • immutable would only change reload behavior in some browsers. For fetch() traffic, max-age is what matters.

    4. Frontend

    • Client.request calls fetch() with no cache option and only Accept and Content-Type headers (static/app/api.tsx:309-318,508-521). That is the default mode, so the browser HTTP cache is honored. A grep of static/app and static/gsApp found no no-store, no-cache, Cache-Control, or Pragma on requests.
    • TanStack Query already treats these resources as immutable within a page session: staleTime: Infinity for specific event IDs (views/issueDetails/useGroupEvent.tsx:39), trace items (views/explore/hooks/useTraceItemDetails.tsx:229), and event attachments (actionCreators/events.tsx:248). The client default is otherwise staleTime 0 with no focus or reconnect refetch (utils/queryClientConfig.tsx:19-34). The HTTP cache therefore mostly helps across reloads, tabs, and in-memory cache evictions (gcTime defaults to 5m), and for non-browser clients such as the CLI, which could drop its TTL tiers wherever the header is present.
    • Frontend alternative: the IndexedDB query persister exists but only persists bootstrap-projects (appQueryClient.tsx:51-71). Persisting event or trace-item queries would give similar wins without server changes. It carries the same staleness, logout, and privacy problems, and clearQueryCache would need to run on logout.

    5. Rollout

    1. Land feat(api): Add opt-in max-age mode to ConditionalGetResponseMixin #128828. It is a no-op by default.
    2. Confirm api.conditional_get.enabled is on. Watch api.conditional_get{endpoint,mode,result} and the body_bytes distribution.
    3. Add one endpoint at a time to api.conditional_get.max_age_endpoints, starting with ProjectTraceItemDetailsEndpoint. A browser cache hit never reaches the server, so measure success as a drop in per-endpoint request rate and p95 page-load time, not as server-side hits.
    4. Rollback: remove the endpoint from the list. Responses already cached live for up to max-age, which is why N starts at 300s. Only raise N (for example to 3600) after deciding that up to N of stale access after member removal or deletion is acceptable.

    Open questions

    • Is api.conditional_get.enabled on in production, and what is the autofix hit ratio? That ratio is the best available proxy for how often Vary: Cookie matches.
    • Security and privacy sign-off on N: how long a removed member, or a GDPR deletion, may still be served from that browser's cache.
    • Are the project and group event details worth splitting? Moving nextEventID/previousEventID, userReport, and release to separate requests would make the event payload itself cacheable.
  3. self-assigned this
    on Oct 28, 2026
  4. sentry-junior commented on Oct 28, 2026

    @sentry-junior
    ContributorAuthor

    Progress update

    #128828 is ready for review. I rebased it onto current master (it was 208 commits behind, with no conflicts). CI passes on 7121dcc: 73 checks pass, 16 skipped, 0 failing. The one red status on the old head, snapshots/upload, failed in the upload step with Path is not a directory: .artifacts/snapshots. That is CI infra, not this PR, and it passes on the new head. The PR has no review comments or threads yet. The only thing blocking it is the required review.

    Local run on the rebased branch: the five pytest files in the PR body pass (165 passed, 1 xpassed), and prek plus the pre-push mypy hook pass on the changed files.

    Open questions

    1. Is api.conditional_get.enabled on in prod? Yes, as far as config shows.

    • src/sentry/options/defaults.py registers it with default=False.
    • sentry-options-automator sets api.conditional_get.enabled: true in options/default/app.yaml. It was added in getsentry/sentry-options-automator#9466 (merged 2026-08-31), and no region file overrides it. I checked the automator's desired state, not live option values. The metric below shows the option is in effect.

    Autofix hit ratio, from Datadog sentry.api.conditional_get, last 7 days:

    endpoint result requests body bytes (approx.)
    GroupAutofixEndpoint hit (304) 486,947 ~7.9 GB not sent
    GroupAutofixEndpoint miss (200) 1,774,641 ~6.4 GB sent
    • That is a 21.5% hit ratio by request. By bytes, about 55% of autofix body bytes were never sent. A 304 averaged about 16 KB and a 200 about 3.6 KB. My guess is that large, finished autofix states are polled again while they stay unchanged. The byte figures come from a Datadog distribution sum, so read them as estimates.
    • GroupAutofixEndpoint is the only endpoint reporting the metric today. The two endpoints in feat(api): Add opt-in max-age mode to ConditionalGetResponseMixin #128828 will report under mode:max_age once they are deployed and listed in the option.

    2. Security/privacy sign-off on N = 300. Still open, and only a person can close it. The automated reviews (warden: security-review, warden: wrdn-authz, Semgrep, CodeQL) pass on the PR, but they don't count as sign-off. The review requests went to issue-detection-backend, issues-feed, data-browsing, and app-backend. None of those is a security reviewer.

    3. Split project/group event details to make them cacheable? Still a product decision for the issues team. Since the spike, I confirmed one thing in code: the frontend reads nextEventID/previousEventID only through static/app/utils/events.tsx and static/app/views/issueDetails/eventNavigation/issueDetailsEventNavigation.tsx, so moving those two fields would touch a small area. userReport and release still come from live rows (api/serializers/models/event.py). This step is not needed for the current rollout, which covers only org event details and trace item details.

    Still blocked

    • Review on feat(api): Add opt-in max-age mode to ConditionalGetResponseMixin #128828 from a code owner of src/sentry/api/ plus one of the endpoint owners: data-browsing for trace item details, issues for org event details.
    • Security/privacy sign-off on private, max-age=300 with Vary: Cookie, Authorization, Origin, and on the superuser/staff fallback.
    • After merge: add ProjectTraceItemDetailsEndpoint to api.conditional_get.max_age_endpoints in sentry-options-automator, then watch sentry.api.conditional_get{endpoint,mode,result} and body_bytes before adding OrganizationEventDetailsEndpoint. This needs an owner to make the option change. I have not changed any options.

    I'm not opening a new PR. Every remaining step needs a review, a sign-off, or a product decision.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions