feat: add FastAPI middleware for per-request emissions tracking#1203
feat: add FastAPI middleware for per-request emissions tracking#1203davidberenstein1957 wants to merge 21 commits into
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #1203 +/- ##
==========================================
- Coverage 89.70% 89.12% -0.59%
==========================================
Files 48 51 +3
Lines 4778 4945 +167
==========================================
+ Hits 4286 4407 +121
- Misses 492 538 +46 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
Hello, thanks for this. There is a problem with your branch : there are many changes that are already merged. Can you do a rebase ? |
f44740f to
15c0ccf
Compare
|
@benoit-cty I have reached out to some people at FastAPI, if they would be interested in a quick review :) For visibility, we could also consider deploying it as a standalone integration, but let's see if people like it. |
eabd526 to
bb6995c
Compare
SaboniAmine
left a comment
There was a problem hiding this comment.
Thanks David this a great PR! Left a few questions, and saw that you have already prepared a benchmark script, do you have any numbers / graph already computed to share ?
250881f to
deba2ce
Compare
Ship optional codecarbon[fastapi] integration with CodeCarbonMiddleware, configurable response headers, route-based task naming, and lifespan helper for shared app-level tracking. Co-authored-by: Cursor <cursoragent@cursor.com>
Add tests for app tracking mode, deprecated include_emissions_header, on_request_complete callbacks, header preset edge cases, and routing formatters so Codecov patch coverage meets the PR threshold. Co-authored-by: Cursor <cursoragent@cursor.com>
…iltering Update the FastAPI middleware to support include and exclude patterns for request tracking, allowing users to specify which endpoints to measure. Refactor routing helpers for improved clarity and add support for deferred measurement. Update documentation to reflect new features and usage examples. Co-authored-by: Cursor <cursoragent@cursor.com>
Refactor FastAPI middleware and routing code for improved readability by adjusting line breaks and indentation. Remove the product telemetry link from the documentation navigation. Update test cases for consistency in formatting and structure.
Refactor the test for FastAPI middleware to handle deferred task execution using a thread pool. This change enhances the test's reliability by ensuring that asynchronous tasks are properly awaited in a separate thread, improving overall test coverage and stability.
Refactor the exception handling in gpu_amd.py to specifically catch AttributeError when importing amdsmi. Update the warning message to provide clearer guidance on ensuring proper configuration of amdsmi for AMD GPU metrics.
Document latency for sync vs deferred logging on a MiniLM embedder workload and add a reproducible scripts/benchmark_fastapi_middleware.py runner. Co-authored-by: Cursor <cursoragent@cursor.com>
…ions logging Add support for tracking HTTP requests in the FastAPI middleware, including a new `HttpRequestBaseline` dataclass for capturing request metrics. Implement methods for starting and finishing HTTP request tracking, allowing emissions data to be logged after the response is sent. Update middleware to handle task naming and emissions data persistence, improving overall emissions tracking capabilities. Co-authored-by: Cursor <cursoragent@cursor.com>
…path" This reverts commit 0c34475.
Introduce a new script for benchmarking GPU monitoring overhead, comparing heavyweight NVML calls with a lightweight utilization-only approach. The script measures unnecessary NVML calls in the _monitor_power() hot path and evaluates latency differences. It supports various modes, including quick runs, full benchmarks, and simulated multi-GPU environments, while providing detailed reporting on NVML call breakdowns and performance metrics.
deba2ce to
86cc355
Compare
Clarify the behavior of emissions measurement in FastAPI middleware, emphasizing that tracking occurs after the response is sent. Update descriptions for `create_codecarbon_lifespan` and logging options, and improve benchmark section to reflect average response times with and without middleware. Enhance readability and consistency throughout the document.
|
@inimaz This is ready for review. Rebased on v3.2.9 and benchmarked on a real HF embedder workload — middleware adds about 3 ms per request (~24 ms → ~27 ms). Details in the updated PR description and docs/how-to/fastapi.md. |
Update GPU monitor tests to mock get_gpu_details after perf revert, reset logger level in FastAPI middleware test after CLI monitor sets ERROR level, and clear CODECARBON_TELEMETRY env vars in config tests.
Move FIELD_UNITS, HEADER_PRESETS, and HTTP methods into codecarbon.core.emission_fields so FastAPI headers/routing reuse shared StrEnums. Simplify resolve_header_mapping with match dispatch and keep backward-compatible dict exports.
|
@SaboniAmine Thanks again for the thorough review — I've addressed the inline threads in the latest pushes:
Local |
Remove unused header/enum stack. Opt-in response_headers measures before response.start. include_background_tasks toggles whether finalize waits for Response.background. Docs clarify BG vs WebSockets.
|
Ponytail cleanup on this PR:
See |
Document ~+25 ms at c=1 and ~+65 ms at c=4 for sync headers with a mocked 20 ms sample, and keep placeholder project/experiment UUIDs.
|
Added a sync
Reproduce: |
Document measured deferred vs sync-headers latency on a real MiniLM workload, and harden tracker shutdown against cancelled futures.
Keep a static measured-overhead overview in the docs; remove the reproducibility commands and the large benchmark harness.
Summary
codecarbon[fastapi]integration: middleware to track CO₂ emissions per HTTP request on FastAPI/Starlette appscreate_codecarbon_lifespanfor a shared app-level tracker, route include/exclude filters, optionalsave_to_api, and opt-inresponse_headersparaphrase-MiniLM-L3-v2): default deferred middleware ~+4 ms per request; sync headers cost more. See docs/how-to/fastapi.md.Test plan
uv run pytest tests/integrations/ -vuv run --extra fastapi uvicorn examples.fastapi_middleware:app --reloadthencurl localhost:8000/predictUsage
Full guide: docs/how-to/fastapi.md