Designing a Real-Time Buying Power Engine with Kafka
Ajaib · Senior Software Engineer · Jul 2023 – Dec 2024 · Java, Spring Boot, WebFlux, Kafka, MySQL, Redis
The Problem
At Ajaib, one of Indonesia's largest retail brokerage platforms, I built Trade Limit—a real-time buying power feature that grants eligible traders dynamic additional limit based on their live trading activity, portfolio holdings, and user profile.
In brokerage systems, buying power sits in an unforgiving spot:
- Too strict / stale low: Eligible traders get wrongly blocked from executing live trades.
- Too loose / double-counted: Traders can over-trade beyond their permitted risk envelope.
Correctness mattered just as much as uptime.
Architectural Principles
1. Keep Calculation Off the Synchronous Trade Path
Calculating updated buying power inline with order placement would couple trading latency and availability to downstream portfolio and limit computations. Instead, Trade Limit runs event-driven: trade executions emit events to Kafka, and the Trade Limit service consumes them asynchronously to recompute each trader's limit.
2. Per-User Ordering, Idempotent Retries & Cached State
Under continuous intraday trading, events arrive in bursts—and duplicate deliveries or consumer retries are expected in distributed messaging systems.
Trade Engine (sync order path)
│
▼ emit trade events (partitioned per user)
Kafka Trade Events
│ ordered per trader within partition
▼
Trade Limit Service (Java / Spring Boot)
├── idempotent event handling (safe retries)
├── combine activity + portfolio + profile
├── persist state to MySQL
└── cache buying power in Redis (TTL + event-driven refresh)
Three design choices kept the state accurate and fast under live brokerage load:
- Per-user ordering: Partitioning Kafka events per user guaranteed that a single trader's state transitions were processed strictly in sequence rather than racing across concurrent workers.
- Idempotent event handling: Retrying a failed message or replaying an event could never double-count a trade's impact on buying power.
- MySQL persistence + Redis caching: Buying power state was persisted in MySQL and cached in Redis with a configured TTL, with targeted cache refreshes triggered whenever relevant events updated a trader's state.
3. Heavy Consumer-Lag Monitoring
In an asynchronous buying-power pipeline, consumer lag is the single biggest driver of state drift. We monitored Kafka consumer lag closely so any processing slowdown or backlog surfaced immediately—before traders experienced stale buying power.
Cutting JVM Memory Usage by ~30%
Alongside feature work on Trade Limit and day-trading capabilities that grew Total Processing Value (TPV), I investigated memory pressure in a core Java / Spring Boot (WebFlux) brokerage service.
Using a Java profiler, I identified hot paths on the Spring WebFlux event loop and refactored the bottlenecked work to process in parallel—cutting the service's memory footprint by ~30%.