Problem
Brokers and trading firms must block orders that breach size, price, position or exposure limits before they are routed to an execution venue. The check sits on the order’s critical path, so it has to be fast, exact, and safe under concurrency: two orders arriving at the same time must never both pass a limit that only one of them fits under.
What I built
A synchronous pre-trade risk gateway in async FastAPI. Every order gets an ACCEPT or REJECT with a per-check breakdown, and accepted quantity is atomically reserved against the account’s position and exposure limits until it is filled or cancelled.
- Nine controls on every order: kill switch, restricted list, order-rate throttle, reference-price freshness, fat-finger size / value / price collar, position limit and gross-exposure limit.
- Controls mapped to the pre-trade categories in SEC Rule 15c3-5 and MiFID II RTS 6.
- Limits live in a YAML rules file, validated with Pydantic and hot-reloaded without a restart.
- Exact
Decimalarithmetic end to end; every failure mode fails closed. - Audit trail, Prometheus metrics, Docker Compose stack and CI.
Architecture
- Each control is a pure function over an immutable snapshot, with no I/O, so every boundary can be tested exhaustively.
- State (positions, reservations, prices, rate windows) lives in Redis. Check-and-reserve uses optimistic
WATCH/MULTI/EXECand re-decides from a fresh snapshot if another writer touched the account’s keys. - Every decision carries a
rules_versionhash, so you can reconstruct which limits applied to any order.
Results
- CI runs a contention test against a real Redis 7: 50 simultaneous 1,000-share orders against a 5,000-share position limit accept exactly 5.
- Latency is dominated by Redis round trips, not computation: an accept or reject takes 7 round trips plus sub-millisecond
Decimalarithmetic, so the service is designed to sit next to Redis. - A built-in load generator reports throughput and p50 / p90 / p99 / p99.9 latency, and CI runs it against the Docker Compose stack on every push.
- Invalid rule edits never take effect: the previous rules stay in force and the problems are reported at
/admin/rules.
Tech stack
- Service: Python, async FastAPI, Pydantic
- State: Redis 7 (
WATCH/MULTI/EXECtransactions, Redis Cluster-ready key layout) - Rules: YAML parsed straight to
Decimal, hot-reloaded - Ops: Docker Compose, Prometheus metrics, structured JSON logs, GitHub Actions CI




