Read each rule's latest order through a LATERAL instead of aggregating every order - #4716
Merged
Merged
Conversation
davidleomay
force-pushed
the
fix/trading-rule-latest-order-lateral
branch
from
August 6, 2026 16:32
a3f83cb to
e743326
Compare
davidleomay
marked this pull request as ready for review
August 7, 2026 09:56
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TradingJobService::processRulesruns every minute and callsgetCurrentTradingOrders, which asked PostgreSQL forMAX(id) GROUP BY tradingRuleIdacross the wholetrading_ordertable. DFXServer/server#1223 measured it at roughly 0.5 s a run, 20 runs over 100 ms within 75 minutes.Why the existing index did not fix it
The composite index on
trading_order ("tradingRuleId", "id")(#4497, merged 30 July) is already in place and was live during that measurement. It does not help, because PostgreSQL has no skip scan: a per-groupMAXreads the index end to end. The cost grows with the number of orders, which is unbounded, while the answer only ever has as many rows as there are rules.The change
Driven from
trading_ruleinstead, with aLATERALthat descends the same index once per rule and stops at the first row:Cost now grows with the number of rules — configuration, and small.
Still one statement, which is a correctness requirement rather than a preference. The previous comment records why:
LogJobServicewrites the FinanceLog from this result, so every rule's latest order has to come from the same READ-COMMITTED snapshot. A per-rule loop would be faster to write and would quietly break that, mixing rows from different points in time. ALATERALis a single statement under a single snapshot, so the property survives.Set semantics are unchanged from the
INNER JOIN: driving fromtrading_ruledrops orders whose rule no longer exists, and a rule with no orders contributes nothing because its lateral subquery returns no row.Raw SQL because
LATERALhas no query-builder equivalent. There is precedent for raw reads in this codebase (24 call sites, e.g.bank-tx.service.ts:597).The test engine had to move, and that is part of the change
The previous implementation comment said not to write this query without first solving pg-mem, and that was accurate — I checked rather than assuming. pg-mem cannot execute a
LATERAL: it fails to resolve the subquery's reference to the outer row withcolumn "rule.id" does not exist.So
trading-rule.service.pg.spec.tsbecomestrading-rule.service.latest-orders.spec.ts, running against a real PostgreSQL behindMIGRATION_TEST_PG— the same gate the migration and projection specs use. All three original assertions are carried over unchanged: highest id per rule with empty rules and orphans excluded, empty table returning an empty array, and no null or undefined ids reachingfindBy In(...).Two assertions are added. One covers rules existing while none has an order — the case that separates
CROSS JOIN LATERALfromLEFT JOIN LATERAL, where the latter would produce a null id and carry it intoIn(...). The other is anEXPLAINassertion that the plan is a nested loop over the rules and contains no aggregate, so a future revert toMAX … GROUP BYfails there while every behavioural assertion still passes.The cost is real and worth stating plainly: these assertions ran on every machine before and now skip without
MIGRATION_TEST_PG. They run in CI, which is also the only place the plan assertion means anything.What is not verified
That this is faster in production. Dev holds zero trading rules and zero orders, and I have no production access, so there is no before/after timing here — only the plan shape, asserted in CI. The argument for the change is structural: the old form's cost scales with a table that grows without bound, the new form's with one that does not.
No entity, column or DTO changes, so nothing else in the completeness list applies. No
@DfxCronchange:TradingJobService::processRulesis untouched.