PR Review Lab · Replace JSON With a Binary Quote Protocol

35:00left of 35:00

Replace JSON With a Binary Quote Protocol

JSON encoding and decoding is 9% of CPU on the quote service. This adds a small wire crate that encodes quote requests as length-prefixed fields in a fixed order, and switches the gateway to it. In a microbenchmark, encode and decode are 6x faster than serde_json, and staging p99 dropped by 4 ms. Both services deploy from the monorepo, so they ship together.

Acrates/wire/src/lib.rs1 of 3

Files Changed

crates/wire/src/

services/gateway/src/

crates/wire/tests/

crates/wire/src/lib.rs

Rust · Click a line number to comment · Tap a line to comment
@@ -0,0 +1,36 @@
Added: //! Compact binary encoding for quote requests between the gateway and the quote service.
Added:
Added: use std::io::{self, Read, Write};
Added:
Added: pub struct QuoteRequest {
Added: pub sku: String,
Added: pub quantity: u32,
Added: pub region: String,
Added: }
Added:
Added: pub fn write_request<W: Write>(w: &mut W, req: &QuoteRequest) -> io::Result<()> {
Added: write_str(w, &req.sku)?;
Added: w.write_all(&req.quantity.to_ne_bytes())?;
Added: write_str(w, &req.region)
Added: }
Added:
Added: pub fn read_request<R: Read>(r: &mut R) -> io::Result<QuoteRequest> {
Added: let sku = read_str(r)?;
Added: let mut quantity = [0u8; 4];
Added: r.read_exact(&mut quantity)?;
Added: let region = read_str(r)?;
Added: Ok(QuoteRequest { sku, quantity: u32::from_ne_bytes(quantity), region })
Added: }
Added:
Added: fn write_str<W: Write>(w: &mut W, s: &str) -> io::Result<()> {
Added: w.write_all(&(s.len() as u32).to_ne_bytes())?;
Added: w.write_all(s.as_bytes())
Added: }
Added:
Added: fn read_str<R: Read>(r: &mut R) -> io::Result<String> {
Added: let mut len = [0u8; 4];
Added: r.read_exact(&mut len)?;
Added: let mut buf = vec![0u8; u32::from_ne_bytes(len) as usize];
Added: r.read_exact(&mut buf)?;
Added: Ok(String::from_utf8(buf).unwrap())
Added: }