Skip to content

perf: replace format!() allocations in on_headers hot path - #1200

Merged
FlorentinDUBOIS merged 4 commits into
mainfrom
perf/on-headers-optimization
Mar 17, 2026
Merged

FlorentinDUBOIS merged 4 commits into
mainfrom
perf/on-headers-optimization

Conversation

@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator

Summary

  • Replace 7 format!() allocations with itoa::Buffer, write!() into Vec<u8>, and extend_from_slice
  • Add itoa workspace dependency (zero-dep, stack-based integer formatting)
  • Extract write_forwarded_for_by and write_forwarded_suffix helpers to reduce code duplication

Review fixes applied

  • Removed unnecessary unsafe { from_utf8_unchecked(...) }.as_bytes() roundtrip — now uses &[u8] directly
  • Moved Vec::with_capacity(128) allocation into conditional scope (was allocating on every request even without session_address)
  • Fixed misleading "reusable buffer" comment

Closes #1140

Test plan

  • cargo test --workspace passes
  • cargo clippy --workspace clean
  • E2e tests pass (20/20)

Replace heap-allocating format!() calls with write!() into reusable
Vec<u8> buffers and itoa for stack-based integer formatting. This
eliminates up to 7 String allocations per HTTP request in the header
editing callback that profiling showed taking up to 75% of readable().

Changes:
- Add itoa dependency for stack-based u16 port formatting
- Add write_forwarded_for_by() and write_forwarded_suffix() helpers
  that build Forwarded header values into a Vec<u8> without format!()
- Replace format!() in X-Forwarded-For, Forwarded, Set-Cookie with
  write!() into reusable hdr_buf + Store::from_vec(take(&mut buf))
- Replace public_port.to_string() with itoa::Buffer for X-Forwarded-Port
- Replace val.to_string() with ToOwned::to_owned for sticky cookie
- Keep self.id.to_string() for Sozu-Id (Ulid encoding is already
  optimized with pre-allocated crockford base32 buffer)
- Remove `unsafe { from_utf8_unchecked(...) }.as_bytes()` round-trip
  when extending hdr_buf with existing header data — the data is
  already `&[u8]`, so the unsafe conversion to `&str` and back was
  pointless and introduced gratuitous unsafety.
- Move `hdr_buf` allocation inside `if let Some(peer_addr)` block to
  avoid a 128-byte heap allocation when `session_address` is `None`.
- Fix misleading "Reusable buffer" comment — the buffer's ownership
  is transferred via `take`, so it is not actually reused.
- Remove unused `from_utf8_unchecked` import.

Signed-off-by: Florentin Dubois <[email protected]>
Align itoa dependency version with workspace convention: "^x.y.z"
instead of "^x.y".

Signed-off-by: Florentin Dubois <[email protected]>

@llenotre llenotre 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.

Vec::with_capacity is allocating memory, just like creating a String. The difference being that format! pre-computes the amount of memory required in the string to avoid re-allocations on grow.

As such, I think the changes in this PR give the same behaviour, but with more complicated code while potentially being less optimized?

@FlorentinDUBOIS FlorentinDUBOIS left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Thanks for the review! The concern is fair, but format!() doesn't actually pre-compute the exact capacity needed.

Looking at the Rust source, estimated_capacity() only sums literal string parts — placeholders like {peer_ip} contribute zero. It also has a special case: when the format string starts with a placeholder and literals total < 16 bytes, it returns 0 (source — String::with_capacity(estimated_capacity())).

In practice for this PR's hot path:

Call Estimated capacity Actual output
format!("{}, {peer_ip}", value) 0 (starts with {}, 2 bytes of literals < 16) ~30-60 bytes
peer_ip.to_string() / port.to_string() 0 1-39 bytes
format!("{value}, proto=…;by={public_ip}") ~40 (literals × 2) ~80-100 bytes with IPv6

So several format!() calls start from zero allocation and grow through multiple reallocations.

The main win here isn't just Vec vs String — it's the buffer reuse via std::mem::take(): a single Vec::with_capacity(128) is allocated once and reused for multiple header writes, reducing ~7 allocations per request to ~3-4. itoa::Buffer adds further savings by formatting ports entirely on the stack (no heap allocation at all).

The extracted helpers (write_forwarded_for_by, write_forwarded_suffix) also reduce the IPv4/IPv6 duplication that existed in the original code. I'll add a criterion benchmark to back this up with numbers.

Add benchmarks comparing the format!() approach vs Vec<u8> + write!()
+ itoa for building HTTP header values in on_headers.

Measures X-Forwarded-For, Forwarded, X-Forwarded-Port, Set-Cookie, and
full pipeline scenarios with both IPv4 and IPv6 fixtures.

Refs: #1140
Signed-off-by: Florentin Dubois <[email protected]>
@FlorentinDUBOIS

Copy link
Copy Markdown
Collaborator Author

Benchmark results

Added a criterion benchmark (lib/benches/header_formatting.rs) comparing the old format!() approach vs the new Vec<u8> + write!() + itoa path. Run with cargo bench --bench header_formatting.

Benchmark format!() Vec + write! / itoa Speedup
x_forwarded_for (IPv4) 100.7 ns 94.3 ns 6%
x_forwarded_for (IPv6) 120.0 ns 101.8 ns 15%
forwarded (IPv4) 222.2 ns 161.4 ns 27%
forwarded (IPv6) 224.0 ns 151.4 ns 32%
x_forwarded_port 22.5 ns 6.7 ns 3.4x
set_cookie (IPv4) 124.1 ns 18.8 ns 6.6x
set_cookie (IPv6) 145.6 ns 18.7 ns 7.8x
full_pipeline (IPv4) 512.9 ns 345.4 ns 33%
full_pipeline (IPv6) 483.5 ns 326.7 ns 32%

The biggest wins are on set_cookie (6-8x) and x_forwarded_port (3.4x) — exactly the cases where estimated_capacity() returns 0 because the format string starts with a placeholder and has < 16 bytes of literals, so String starts with zero allocation and grows through multiple reallocations.

Full pipeline: ~33% faster per request.

@FlorentinDUBOIS
FlorentinDUBOIS merged commit df50086 into main Mar 17, 2026
22 checks passed
@FlorentinDUBOIS
FlorentinDUBOIS deleted the perf/on-headers-optimization branch March 17, 2026 13:57
jrcribb pushed a commit to jrcribb/sozu that referenced this pull request Aug 10, 2026
…timization

perf: replace format!() allocations in on_headers hot path
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.

Performance optimisation

2 participants