Rust OpenAI-compatible streaming proxy with request coalescing
CPU · your Macscript240 minrequiredGoal · A Rust service that accepts /v1/chat/completions, streams SSE chunks from an upstream (the Phase 5 stub server), coalesces identical concurrent requests into one upstream call, and passes a load test.
- 1cargo new llm_proxy; add axum, tokio, reqwest (stream feature), serde, serde_json, sha2 and tokio-stream.
- 2Define the request and chunk structs with serde matching the OpenAI chat schema (messages, model, stream, max_tokens; choices with delta content).
- 3Implement a handler that forwards the request to the upstream URL and relays SSE chunks to the client as they arrive using a streaming body; verify the first chunk reaches the client before the upstream finishes.
- 4Add coalescing with a DashMap or Mutex<HashMap> keyed by a hash of the canonicalised request body; the first caller creates a tokio broadcast channel and performs the upstream call, later identical callers subscribe to it.
- 5Add a 429 response when in-flight requests exceed a configurable limit, and a /metrics endpoint with request, coalesced and shed counters.
- 6Run cargo clippy and cargo fmt; add an integration test with a mock upstream that counts calls.
- 7Load test with 50 identical concurrent requests and with 50 distinct ones against the stub server, counting upstream requests from the stub's logs.
- Deliverable
- The llm_proxy crate with tests, and a load test log.
- Check
- With 50 identical concurrent requests the upstream receives exactly 1 request and all 50 clients receive the full stream; with 50 distinct requests the upstream receives 50; cargo clippy reports zero warnings; the first SSE chunk is delivered to the client before the upstream stream completes.