✳The starting point
A request has a story.
Your gateway should tell it.
One request can cross Cloudflare, a cloud and a few SaaS APIs. When it fails, the why is scattered across all of them.
What if the gateway explained the traffic it handled?
That's Relay: routing, custom logic, config and inspection in one place, on your infrastructure.
✳Close to the request
A little Rust.
A real limit.
Each API key gets 5 requests a second. The sixth gets a 429. No key gets a 401.
Download the example ↓Native Rust process.
The website itself runs on Workers.
main.rsRust / Pingora 0.9
use async_trait::async_trait;use pingora::http::ResponseHeader;use pingora::prelude::*;use pingora::proxy::{http_proxy_service, ProxyHttp, Session};use pingora_limits::rate::Rate;use std::sync::LazyLock;use std::time::Duration;static RATE: LazyLock<Rate> = LazyLock::new(|| Rate::new(Duration::from_secs(1)));const LIMIT: isize = 5;struct Gateway;#[async_trait]impl ProxyHttp for Gateway { type CTX = (); fn new_ctx(&self) {} async fn request_filter(&self, session: &mut Session, _: &mut ()) -> Result<bool> { let Some(key) = session.req_header().headers.get("x-api-key") else { session.respond_error(401).await?; return Ok(true); }; if RATE.observe(key, 1) > LIMIT { let mut res = ResponseHeader::build(429, None)?; res.insert_header("retry-after", "1")?; res.insert_header("x-ratelimit-limit", LIMIT.to_string())?; session.set_keepalive(None); session.write_response_header(Box::new(res), true).await?; return Ok(true); } Ok(false) } async fn upstream_peer(&self, _: &mut Session, _: &mut ()) -> Result<Box<HttpPeer>> { let app = HttpPeer::new(("127.0.0.1", 3000), false, String::new()); Ok(Box::new(app)) }}fn main() { let mut server = Server::new(None).unwrap(); server.bootstrap(); let mut proxy = http_proxy_service(&server.configuration, Gateway); proxy.add_tcp("127.0.0.1:8080"); server.add_service(proxy); server.run_forever();}
localhost:8080 → localhost:30005 req/s per key