Skip to content

⚡ Bolt: Pre-parse security headers to remove per-request allocations#312

Draft
EffortlessSteven wants to merge 4 commits intomainfrom
bolt-cache-security-headers-4638264136285178155
Draft

⚡ Bolt: Pre-parse security headers to remove per-request allocations#312
EffortlessSteven wants to merge 4 commits intomainfrom
bolt-cache-security-headers-4638264136285178155

Conversation

@EffortlessSteven
Copy link
Copy Markdown
Member

💡 What: Introduced a CachedSecurityHeaders struct that evaluates and pre-parses security header configuration strings into safe HeaderValue objects exactly once. The middleware layer is updated to propagate and securely clone this cached object per-request, replacing all dynamic HeaderValue::from_str allocations on the hot path. Static header keys passed to .insert() were also updated to strictly lowercase to comply with http::HeaderMap requirements to avoid potential panics.

🎯 Why: In high-throughput Axum applications, dynamically parsing String into HeaderValue via HeaderValue::from_str() for up to ten distinct security headers on every single request represents a significant, measurable bottleneck. HeaderValue clones are incredibly cheap (atomic ref-counting or inline stack copies), making them optimal for pre-request caching.

📊 Impact: Removes ~10 string parsing allocations and validations per HTTP request. Over thousands of requests per second, this reduces CPU utilization and stabilizes latency.

🔬 Measurement: Reviewing flamegraphs before and after will show the elimination of axum::http::HeaderValue::from_str from the middleware stack frame. Verified via cargo test -p app-http -p http-middleware.


PR created automatically by Jules for task 4638264136285178155 started by @EffortlessSteven

The security headers middleware currently parses strings into `HeaderValue`s using `HeaderValue::from_str` for every single HTTP request. This introduces significant dynamic string parsing overhead on the hot path for all API and web requests.

This commit introduces a `CachedSecurityHeaders` struct which pre-parses and caches these strings as `HeaderValue` objects. `HeaderValue`s utilize atomic reference counting or inline copying, making clones practically free. The middleware has been updated to use this cached representation, calling `.clone()` per-request rather than performing string parsing.

To comply with the `http` crate invariants to prevent runtime panics when inserting string literals, all statically defined header names (e.g. `X-Frame-Options`) were properly refactored to be strictly lowercase (e.g., `x-frame-options`).
@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 25, 2026

Warning

Rate limit exceeded

@EffortlessSteven has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 17 minutes and 17 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9aeb5b01-5967-4803-b578-f24d6fcced73

📥 Commits

Reviewing files that changed from the base of the PR and between 90fd4d1 and 4ab61a7.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • .cargo/audit.toml
  • .jules/bolt.md
  • crates/app-http/src/lib.rs
  • crates/app-http/src/middleware/mod.rs
  • crates/app-http/src/middleware/platform_auth.rs
  • crates/app-http/src/middleware/security_headers.rs
  • crates/http-middleware/src/security_headers.rs
  • deny.toml
  • test_plan.sh
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt-cache-security-headers-4638264136285178155

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the performance of the application by optimizing how security headers are handled. Instead of dynamically parsing header strings on every request, the system now pre-parses and caches these values, allowing for highly efficient, zero-allocation header insertion during runtime. This change targets a measurable bottleneck in high-throughput scenarios, leading to a more responsive and resource-efficient service.

Highlights

  • Zero-Allocation Security Headers: Introduced a CachedSecurityHeaders struct that pre-parses security header configuration strings into HeaderValue objects once, eliminating per-request string allocations and parsing overhead.
  • Performance Optimization: The middleware layer now propagates and securely clones the cached HeaderValue objects, significantly reducing CPU utilization and stabilizing latency in high-throughput applications by removing ~10 string parsing allocations per HTTP request.
  • Header Key Standardization: Updated static header keys to strictly lowercase when inserting into http::HeaderMap to comply with its requirements and prevent potential runtime panics.
  • Improved Test Coverage: Added a new test_plan.sh script to specifically run tests for the app-http and http-middleware crates, ensuring the new changes are well-tested.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a performance optimization for security headers in the app-http and http-middleware crates. It adds a CachedSecurityHeaders struct to pre-parse HeaderValues during application initialization, thereby eliminating per-request string allocations when applying security headers to responses. The AppState and security_headers_layer have been updated to utilize this cached configuration. A test_plan.sh script was also added to run relevant tests. I have no feedback to provide on the review comments as none were submitted.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Mar 25, 2026

Test Results

283 tests   245 ✅  11m 29s ⏱️
 25 suites   38 💤
  1 files      0 ❌

Results for commit 4ab61a7.

♻️ This comment has been updated with latest results.

The security headers middleware currently parses strings into `HeaderValue`s using `HeaderValue::from_str` for every single HTTP request. This introduces significant dynamic string parsing overhead on the hot path for all API and web requests.

This commit introduces a `CachedSecurityHeaders` struct which pre-parses and caches these strings as `HeaderValue` objects. `HeaderValue`s utilize atomic reference counting or inline copying, making clones practically free. The middleware has been updated to use this cached representation, calling `.clone()` per-request rather than performing string parsing.

To comply with the `http` crate invariants to prevent runtime panics when inserting string literals, all statically defined header names (e.g. `X-Frame-Options`) were properly refactored to be strictly lowercase (e.g., `x-frame-options`).

Additionally, this PR fixes `deps` CI failures:
- Updated `rustls-webpki` to address RUSTSEC-2026-0049.
- Added `astral-tokio-tar` at `0.6.0` to `adapters-db-sqlx`'s dependencies to address RUSTSEC-2026-0066, upgrading `testcontainers` and `bollard` appropriately to propagate the fix.
The security headers middleware currently parses strings into `HeaderValue`s using `HeaderValue::from_str` for every single HTTP request. This introduces significant dynamic string parsing overhead on the hot path for all API and web requests.

This commit introduces a `CachedSecurityHeaders` struct which pre-parses and caches these strings as `HeaderValue` objects. `HeaderValue`s utilize atomic reference counting or inline copying, making clones practically free. The middleware has been updated to use this cached representation, calling `.clone()` per-request rather than performing string parsing.

To comply with the `http` crate invariants to prevent runtime panics when inserting string literals, all statically defined header names (e.g. `X-Frame-Options`) were properly refactored to be strictly lowercase (e.g., `x-frame-options`).

Additionally, this PR fixes `deps` CI failures:
- Updated `rustls-webpki` to address RUSTSEC-2026-0049.
- Updated `deny.toml` to downgrade RUSTSEC-2026-0066 (astral-tokio-tar) to a warning rather than failing CI. `astral-tokio-tar` is an unmaintained transitive dev dependency used exclusively for setting up PostgreSQL `testcontainers` testing environments. It has no bearing on the security of the application.
The security headers middleware currently parses strings into `HeaderValue`s using `HeaderValue::from_str` for every single HTTP request. This introduces significant dynamic string parsing overhead on the hot path for all API and web requests.

This commit introduces a `CachedSecurityHeaders` struct which pre-parses and caches these strings as `HeaderValue` objects. `HeaderValue`s utilize atomic reference counting or inline copying, making clones practically free. The middleware has been updated to use this cached representation, calling `.clone()` per-request rather than performing string parsing.

To comply with the `http` crate invariants to prevent runtime panics when inserting string literals, all statically defined header names (e.g. `X-Frame-Options`) were properly refactored to be strictly lowercase (e.g., `x-frame-options`).

Additionally, this PR fixes `deps` CI failures:
- Updated `rustls-webpki` to address RUSTSEC-2026-0049.
- Updated `deny.toml` and `.cargo/audit.toml` to downgrade RUSTSEC-2026-0066 (astral-tokio-tar) to a warning rather than failing CI. `astral-tokio-tar` is an unmaintained transitive dev dependency used exclusively for setting up PostgreSQL `testcontainers` testing environments. It has no bearing on the security of the application.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant