Skip to content

feat(Observability): Bind request context for API requests - #9041

Open
khvn26 wants to merge 12 commits into
mainfrom
feat/eng-611-request-context
Open

khvn26 wants to merge 12 commits into
mainfrom
feat/eng-611-request-context

Conversation

@khvn26

@khvn26 khvn26 commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

Thanks for submitting a PR! Please check the boxes below:

  • I have read the Contributing Guide.
  • I have added information to docs/ if required so people know about the feature.
  • I have filled in the "Changes" section below.
  • I have filled in the "How did you test this code" section below.

Changes

In this PR, we add auto-resolution for the following attributes in our structured logs:

  • organisation.id
  • project.id
  • feature.id
  • environment.id
  • environment.key

The above attributes now get resolved automagically for any authenticated request, and bound to all logs emitted during the current request lifetime.

Attribute Bound when Source
user.id the request is made by a user str(request.user.uuid). Master API keys aren't users, so get none (as the issue says)
organisation.id the route has an organisation_pk URL kwarg URL kwarg
organisation.id the request uses a master API key request.user.key.organisation_id
project.id, organisation.id the route has a project_pk one primary key lookup of the project's organisation_id
feature.id the route has a feature_pk URL kwarg
environment.key, environment.id, project.id, organisation.id the route has an environment_api_key one lookup of the environment, joined to its project

The performance hit is estimated at around +11 ms p95 for our busiest endpoints.

We also stop relying on OTel spans as vessels for request context, and use flagsmith-common's utilities instead.

Describe API requests in the request context of flagsmith-common, so
every event and span emitted while handling them carries who makes them
and what they act on, without call sites passing it along:

- `user.id`: the user's UUID, for users. Master API keys aren't users,
  so get none.
- `organisation.id`: the master API key's organisation, on
  authentication; for users, the organisation the permission layer
  resolves, replacing the span attribute it used to set. Users in
  several organisations are not guessed at.
- `project.id`: from the `project_pk` URL kwarg.

DRF authenticates API requests inside the view, so they're bound by
wrapping `APIView.perform_authentication`, rather than in a middleware.

`environment.id` is not bound: resolving it from `environment_api_key`
costs a query, or an environment cache lookup, per request, and views
already resolve the environment in many different places.

Also:

- List `RequestContextMiddleware` first in `MIDDLEWARE`, under its new
  name, replacing the deprecated `RouteLoggerMiddleware` alias.
- `ClientUsageLoggerMiddleware` reads the organisation from the request
  context, so `telemetry.spans` goes.
- `code_references.scan.created` no longer passes `organisation__id`,
  as the request context always carries the same one.
@vercel

vercel Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
docs Ready Ready Preview Nov 25, 2026 6:59pm UTC
flagsmith-frontend-preview Ready Ready Preview Nov 25, 2026 6:59pm UTC
flagsmith-frontend-staging Ready Ready Preview Nov 25, 2026 6:59pm UTC

Request Review

@linear-code

linear-code Bot commented Nov 20, 2026

Copy link
Copy Markdown

ENG-611

@github-actions github-actions Bot added api Issue related to the REST API docs Documentation updates feature New feature or request and removed docs Documentation updates labels Nov 20, 2026
@codecov

codecov Bot commented Nov 20, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.93%. Comparing base (0c37fca) to head (75e5ccf).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff            @@
##             main    #9041    +/-   ##
========================================
  Coverage   98.93%   98.93%            
========================================
  Files        1716     1720     +4     
  Lines       72808    72961   +153     
========================================
+ Hits        72031    72184   +153     
  Misses        777      777            

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Bind what an API request acts on from its URL, best effort, rather than
from whichever permission checks its view happens to run, which left
the organisation unbound on many routes, e.g. listing a project's
features:

- `project_pk`: the project, and its organisation, with a primary key
  lookup.
- `feature_pk`: the feature.
- `environment_api_key`: the environment, its project and organisation,
  with one lookup.

Most of these views load the project or environment anyway, but in too
many different places to reuse. Deleted entities resolve to nothing.

The permission layer no longer binds the organisation.
@github-actions github-actions Bot added docs Documentation updates feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 24, 2026
Split resolving what an API request acts on in two:

- `map_view_kwargs_to_resolved_ids` maps a view's URL kwargs to the IDs
  they carry, without querying.
- `telemetry.services.get_resolved_ids` resolves, from the database,
  only the IDs missing that the ones present imply: an environment's
  project and organisation, a feature's project and organisation, a
  project's organisation.

Resolving a feature's project also binds the project and organisation
on routes that only identify the environment by ID, e.g. publishing an
environment feature version.

The environment's API key is used to resolve its IDs, but isn't bound.
@github-actions github-actions Bot added docs Documentation updates feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 24, 2026
…ppers`

Also resolve the organisation of soft-deleted projects, as including
them is harmless, and simplify `get_resolved_ids`' docstring.
@github-actions github-actions Bot added docs Documentation updates feature New feature or request and removed feature New feature or request docs Documentation updates labels Nov 24, 2026
@khvn26
khvn26 marked this pull request as ready for review November 24, 2026 20:00
@khvn26
khvn26 requested review from a team as code owners November 24, 2026 20:00
@khvn26
khvn26 requested review from emyller and removed request for a team November 24, 2026 20:00
@github-actions github-actions Bot removed the feature New feature or request label Nov 24, 2026
@github-actions github-actions Bot added the docs Documentation updates label Nov 25, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 4 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@khvn26

khvn26 commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

Before we resort to monkey-patching DRF, I'd like to exhaust other alternatives.

@emyller Sorry for not communicating this clearly, but I did explore a bunch of alternatives before stopping in this solution, and it's actually not bad, IMO.

There's no way for a middleware to access request.user before the view is processed and after it's been authenticated. perform_authentication is really the only correct place for this. To avoid monkeypatching, we could extend the existing classes we use (e.g. with a mixin). I'm not against switching to a mixin, but to me it's no less uglier than a monkeypatch tbh, and we'll have to remember to do that for every class we use in the future.

Regarding ContextVar: it's pretty much what happens under the hood, we're riding structlog's own contextvar. It's an implementation detail for common.core.request_context.bind_request_context and, IMO, is out of scope for this PR.

`str.isdigit` accepts characters, e.g. `²`, that `int` can't parse,
so a router-captured `project_pk` or `feature_pk` like that failed the
request with a `ValueError`. Accept decimal characters only.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 3 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 8 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

Per review, they were unneeded or, about the environment's API key,
misleading.
@khvn26
khvn26 force-pushed the feat/eng-611-request-context branch from 7323e54 to f45f114 Compare November 25, 2026 17:54

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 7 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

…tributes`

It holds more than IDs, e.g. the environment's API key, and "resolved
IDs" didn't say what for. Rename the functions producing it to match:
`map_view_kwargs_to_telemetry_attributes`, and
`get_resolved_telemetry_attributes`.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 6 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

Bind it as `environment.key` on routes identifying the environment by
its API key, alongside `environment.id`. The key is public, and
`environment.key` is how events already report it, e.g. feature
dependency events.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 8 files (changes from recent commits).

Reply with feedback, questions, or to request a fix.

Turn on auto-fix | Re-trigger cubic

Comment thread api/telemetry/mappers.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 2 unresolved issues from previous reviews.

Turn on auto-fix | Re-trigger cubic

@khvn26
khvn26 force-pushed the feat/eng-611-request-context branch from 1a1bc6a to c063801 Compare November 25, 2026 18:17
Map `organisation_pk` to `organisation.id`, like `project_pk` to
`project.id`. It's in the URL, so it needs no query.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

Turn on auto-fix | Re-trigger cubic

Django calls `ready` again when it sets up its apps again, e.g. in tests
overriding installed apps, which wrapped `APIView.perform_authentication`
once more each time, resolving and binding request context repeatedly.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0 issues found across 2 files (changes from recent commits).

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

Turn on auto-fix | Re-trigger cubic

…context

# Conflicts:
#	api/telemetry/services.py
@emyller

emyller commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Sorry for not communicating this clearly, but I did explore a bunch of alternatives before stopping in this solution, and it's actually not bad, IMO.

My apologies, my review sounded like you have not considered other alternatives.

Regarding ContextVar: it's pretty much what happens under the hood, we're riding structlog's own contextvar. It's an implementation detail for common.core.request_context.bind_request_context and, IMO, is out of scope for this PR.

I wouldn't aim at structlog's contextvar:

  1. In common.core.request_context, we add a new _current_request = ContextVar().
  2. In RequestContextMiddleware.process_view, we set _current_request.
  3. In a new structlog processor:
    1. We _current_request.get(), and check if its .user is authenticated.
    2. Then we can bind_request_context(user__id=...) — or organisation__id.

The practical effect I'd expect is that in every log emitted, we check whether the stored request has an authenticated user, and enrich the log context with it if it's not already.

Monkey-patching the exact moment looks smart but it hurts traceability. Mixins are out of question — we're not even 100% CBV.

@emyller emyller left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After an offline discussion, I still keep my preference for a contextvar + log processor approach, but won't hold my opinion against monkey-patching strongly. Thanks for addressing the other comments!

This branch was successfully deployed

3 active deployments
Preview – flagsmith-frontend-staging — 75e5ccfd Deployed Nov 25, 2026 by vercel[bot]
Preview – flagsmith-frontend-preview — 75e5ccfd Deployed Nov 25, 2026 by vercel[bot]
Preview – docs — 75e5ccfd Deployed Nov 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api Issue related to the REST API docs Documentation updates feature New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants