On this path · Financial Systems 1. The Order Lifecycle in a Brokerage
The Order Lifecycle in a Brokerage
From tap-to-trade through routing, execution, clearing, settlement, and custody, with price-time priority.
Learning outcomes
A customer taps Buy on a phone and, seconds later, owns a fraction of a company. The work that happens in between is the order lifecycle, and almost every senior engineering judgement call at a brokerage traces back to one of its stages. This page teaches that pipeline as a sequence of failure surfaces, not a checklist, so you can reason about what breaks and why.
After studying this page, you can:
- Trace an order from the mobile tap through validation, risk and limits, routing, execution, clearing, settlement, and custody, naming the obligation each stage protects.
- Explain why price-time priority is the rule exchanges settle on, and predict how an engine orders two otherwise equal orders.
- Build a defensible end-to-end latency budget and defend each stage against its dominant failure mode.
- Distinguish a rejection, a partial fill, and a cancellation operationally, and explain why the money state of each differs.
- Defend the lifecycle design against the follow-up questions an experienced interviewer asks, and avoid the documented mistakes that sink candidates.
Before we dive in
Imagine you are the engineer on call the morning a customer places a buy order for one hundred shares, the app shows the order accepted, and then the market closes. Did the customer buy the shares or not? That question, simple to ask and brutal to answer, is the reason the order lifecycle exists as a strict pipeline rather than a single function call.
The lifecycle exists because a brokerage is not one program. It is a chain of independent parties, each with its own obligations, clocks, and failure modes. The customer believes the order is one action. The law, the exchange, the clearing house, and the custodian each see it as a handoff between systems that do not trust each other. Every stage in the lifecycle is a contract boundary where one party hands obligation to another, and each boundary is a place where the order can be lost, duplicated, half-completed, or reversed.
Two forces shaped this chain into its modern form. The first is regulation. A German regulated brokerage like Trade Republic operates under MiFID II, BaFin oversight, and client-asset segregation rules that forbid the broker from co-mingling customer money with its own. Those rules force physical separation of cash, positions, and records at specific lifecycle stages, which is why clearing and settlement are distinct steps and why custody is a separate party. The second force is operational risk. A broker that routes an order without first checking the customer has sufficient buying power can be left holding a loss it cannot recover, so validation and risk checks moved upstream of routing, not as an optimization but as a guard against bankruptcy.
The lifecycle you will study here is therefore not the fastest possible path from tap to trade. It is the fastest path that survives audit, regulation, and the failure of any single component in the chain. Understanding why each stage is where it is, and what breaks if you move or merge it, is the core of brokerage engineering judgement.
Breaking it down
1. The seven stages, from tap to custody
Walk a single market order through the pipeline and you meet seven stages, each with a clear obligation. The mobile client sends an intent to buy. The order service validates the intent is well-formed and authentic. A risk and limits stage confirms the customer can pay for the trade and is within product, concentration, and regulatory limits. A router chooses a venue. The execution stage matches, or partially matches, the order against the book. Clearing reconciles what was traded against what must be delivered and paid. Settlement, one or two business days later, actually moves cash and securities. Custody holds the resulting position for the customer.
Read this diagram as a chain of handoffs, not a flowchart of one program. The validation stage protects the service from malformed or unauthenticated input. The risk stage protects the broker’s solvency by refusing orders the customer cannot honour. Routing protects best-execution obligations under MiFID II. Execution is where the trade legally happens. Clearing and settlement protect the transfer of value. Custody protects the durable record of ownership.
The crucial insight is that these stages are not a refactor someone did for cleanliness. They exist because each is owned by a different legal or operational entity, and each can fail independently. A router can pick a venue that then crashes; the order service must still know the order was routed and must reconcile the outcome. Settlement can fail because a corporate action froze the security, even though execution succeeded hours earlier. Treating the lifecycle as one atomic operation is the first and most common mistake, because no single transaction spans the exchange, the clearing house, and your database.
The value of naming seven stages is not pedantry. It tells you exactly which subsystem to blame when a customer reports the order went wrong, and which guarantee you must reconstruct when a stage fails. A senior engineer’s first instinct on any order incident is to locate which stage produced the wrong state, because the recovery procedure is different at each.
2. Price-time priority and why it dominates
Once an order reaches a venue, the matching engine decides who trades with whom. The rule nearly every exchange uses is price-time priority, often called FIFO matching. The best price trades first, and among orders at the same price, the earliest arrival trades first. Price-time priority is the spine of order matching, and it is the exact rule the documented Trade Republic interview prompt asks you to design an engine around.
Why does price-time win as the convention? Price priority rewards the participant willing to give the most value to the other side, which keeps spreads tight and markets liquid. Time priority, the tiebreaker, rewards speed and fairness: if two sellers offer the same price, the one who got there first is served first, so no participant is disadvantaged by arbitrary reordering. Together they give every participant a deterministic, auditable rule for who gets filled, which is a regulatory requirement, not a performance optimization.
Consider a buy side of a book with two orders: one for two hundred shares at one hundred euros, and one for three hundred shares at one hundred and one euros. A new sell order for two hundred and fifty shares at ninety-nine euros arrives. Price priority sends it to the highest bidder first. The two-hundred-share buy fills completely, and the remaining fifty shares fill against the next best price, the one hundred and one euro bid. The seller got the best possible price for all two hundred and fifty shares. That is price priority doing its job.
The interviewer’s next move is almost always to ask you to implement this ordering and to prove it is deterministic. The trap is treating arrival time as a reliable ordering key. Wall-clock arrival is skewed by network jitter and by separate pod clocks, so a production engine uses a monotonically increasing sequence assigned by the single matching thread or by a sequencer, never the raw timestamp. This is the same lesson Trade Republic learned the hard way with outbox ordering, where sorting by a created_at timestamp across pods broke total order because the clocks were skewed. The matching engine demands the same discipline: sequence numbers, not clocks, define order.
3. The end-to-end latency budget
A senior engineer is expected to reason about latency as a budget, not a single number. The customer perceives the trade as instant, but the work is distributed across stages with very different latency profiles. Validation and risk are in-process database checks, measured in low single-digit milliseconds. Routing adds network hops to a venue, adding tens of milliseconds. Execution at the venue is microseconds for a modern matching engine but you pay the round trip back. Clearing and settlement are not latency-bound at all, they are settlement-cycle-bound, measured in business days.
A realistic budget for the synchronous, customer-facing path, the tap to the order accepted response, is well under a second. Trade Republic’s own published targets illustrate the discipline: instrument search and recommendation must return in under forty milliseconds, and real-time quote streaming must feel continuous. The order placement path is looser than search but still bounded by the expectation that a mobile tap returns an accepted state promptly, or the customer retries and creates duplicate orders.
The budget breaks when you misclassify a stage. If you treat risk as fast because it is in-process, but the limits check joins a slow external KYC or sanctions service, your synchronous path blocks on an upstream you do not control. If you treat settlement as slow and therefore ignorable, you forget that a settlement failure days later still creates a customer-affecting exception. Budget each stage to its real cost and to its real failure mode, and the design holds; assume they are all alike and the budget is fiction.
4. Where each stage fails
Each stage has a dominant failure mode, and naming them is half of incident response.
Validation fails by rejecting good input or accepting bad input. Rejecting good input is a customer experience problem. Accepting bad input, an order with a negative quantity or a forged customer id, is a safety problem that propagates downstream. Risk fails by letting through an order the customer cannot pay for, leaving the broker on the hook for the difference; this is why buying power is reserved, not just checked, so a concurrent order cannot double-spend the same balance. Routing fails by sending the order to a venue that is down or that gives a worse price, breaching best-execution duties.
Execution fails by partial fill or no fill. An order for one thousand shares may fill two hundred and then the market moves away, leaving the rest unfilled. The lifecycle must support a live, partially-filled state that is neither accepted nor done, and the customer’s money must reflect only the filled portion. Clearing fails when the trade detail does not reconcile between broker and clearing house, which surfaces as a break the next morning and must be investigated and corrected before settlement. Settlement fails when the cash or securities cannot move, because of a frozen account, a corporate action, or a counterparty default, and must be retried or manually resolved. Custody fails by losing or misattributing a position, the worst kind of failure because it is silent until the customer notices.
The most operationally dangerous state is the partial fill that the order service never learns about because the execution acknowledgement was lost. The customer sees the order as pending, the broker’s books show nothing traded, yet the venue has legally executed part of it. This is exactly the dual-write problem in another costume: the venue state and your database state diverged because the acknowledgement did not land in the same atomic step. Reconciliation against the venue, not trust in acknowledgements, is the only durable fix.
5. Partial fills, rejections, and cancellations
These three outcomes are easy to conflate and a senior engineer must keep them distinct, because each leaves the customer’s money in a different state and each requires different recovery.
A rejection is the order never reaching execution. Validation or risk refused it, and no obligation was created. The customer’s reserved buying power, if any was reserved, must be released, and released exactly once. A rejection is the clean case: nothing downstream happened, so nothing downstream must be unwound.
A partial fill is the order reaching execution and matching some, but not all, of its quantity. The filled portion is a real trade that will clear and settle. The unfilled portion may remain on the book, may be cancelled, or may expire; each choice has different money consequences. If the unfilled portion stays on the book, the buying power for it stays reserved. If it is cancelled, that reservation is released. The bug that bites teams is releasing the reservation for the unfilled portion while the filled portion is still awaiting settlement, leaving the customer temporarily over-allocated.
A cancellation is a customer- or system-initiated request to stop an order that has not fully filled. A cancellation is itself an order that can fail. If the cancellation arrives at the venue after the order has already filled, the customer owns shares they thought they cancelled. If the cancellation arrives and the order is partially filled, only the remainder can be cancelled. Treating cancellation as a guaranteed, instant operation is a mistake; it is an asynchronous request against a moving target, and the final state must be confirmed from the venue, never assumed.
Read the state machine as the reason a partial fill and a cancellation leave different money states. A cancellation from the partially-filled state keeps the filled portion, which will settle, and releases only the reservation on the unfilled remainder. A move to filled consumes the entire reservation. The transitions are not instantaneous; each is a confirmed state change from the venue, and your ledger must reflect the terminal state, not the in-flight request.
6. Clearing and settlement, T plus one to T plus two
Execution is the legal trade, but the actual movement of cash and securities happens later, at settlement. The lag is the settlement cycle, historically two business days for equities, the convention written as T plus two, and moving in many markets to T plus one. The lag exists because the parties need time to confirm the trade detail, arrange the delivery of securities, and move cash through payment systems that themselves settle in batches.
Clearing is the reconciliation stage between execution and settlement. The clearing house acts as the counterparty to both sides, guaranteeing the trade so that no one faces the default risk of a stranger. Clearing matches the trade records from both broker and venue, surfaces any discrepancy as a break, and nets obligations so that only the net movement of cash and securities must be settled. For a brokerage, this is where the internal ledger must reconcile against the external clearing house record, and any break is a hard signal that something in execution or in the internal ledger went wrong.
The engineering implication is that your system has two notions of truth for several days. The execution-time truth is what your matching or routing service believes happened. The settlement-time truth is what the clearing house and custodian confirm happened. A correct system treats the settlement-time truth as authoritative for money and positions, and the execution-time truth as provisional, because execution acknowledgements can be lost, duplicated, or reordered, while settlement records are reconciled and netted. Reconciliation jobs that compare internal ledgers against clearing-house files are not optional polish, they are the mechanism by which a brokerage discovers it was wrong about a trade.
Common mistakes candidates make
The documented Trade Republic failure modes name several mistakes directly, and experience adds a few more. A senior candidate avoids all of them.
- Treating the lifecycle as one atomic operation. No transaction spans the exchange, the clearing house, and your database. A design that assumes atomic handoff fails the first time an acknowledgement is lost. The fix is to model each handoff as its own transactional boundary with explicit reconciliation between them.
- Not handling the rollback on failure. If execution fails after buying power was reserved, the reservation must be released. Candidates who skip the unwind leave customers with permanently locked balances. The documented interview feedback flags missing transaction rollbacks as a real failure mode.
- Checking buying power instead of reserving it. A check followed by a later debit allows two concurrent orders to both pass the check and then both debit, overdrawing the account. Reservation, an atomic hold on the balance, is the correct primitive.
- Assuming cancellations are instantaneous. A cancellation races against fills. The final state must be confirmed from the venue.
- Trusting execution acknowledgements over reconciliation. Acknowledgements are at-least-once messages over an unreliable network. The settlement record is the source of truth for money.
- Confusing settlement with execution. Treating the trade as done at execution ignores the day or two of settlement risk and the breaks that surface in clearing.
Once you have described the stages, expect to be pushed on a specific failure. A common follow-up: the execution acknowledgement is lost, the customer retrays, and now two orders are in flight. How do you prevent a double execution? The answer is an idempotency key on the customer intent, so the retry is recognized as a duplicate and deduped before routing. Another follow-up: settlement fails for one trade in a batch. How do you isolate it? The answer is per-trade settlement state and selective retry, never all-or-nothing batch settlement that blocks the good trades on the bad one.
Mastery Questions
Question
A sell order for 250 shares arrives at a book with bids of 200 at 100 euros and 300 at 101 euros. What fills, and at what total?
Answer
Price priority sends the sell to the best bid first. The 200 shares at 100 euros fill completely, then 50 shares fill at 101 euros. Total value is euros. The seller got the best available price at every step.
Sources & evidence5 claims · 3 cited
Full lifecycle from tap to custody, price-time priority, latency budget, failure modes per stage, partial fills and cancellations, clearing and settlement. Grounded in src_tr_interview (prompts, rollback failure mode), src_tr_outbox1 (sequence ordering), src_tr_40ms (latency budget). Unbacked lifecycle-stage-split reasoning marked internal-reasoning.
- The documented Trade Republic system-design prompt is an order matching engine with price-time priority that updates accounts and holdings.verified
- Sorting outbox messages by created_at across pods breaks total ordering because pods have skewed clocks; a database sequence id is the correct ordering key, the same principle that governs matching-engine ordering.verified
- A documented candidate failure mode is not handling transaction rollbacks on failure, leaving customers with permanently locked balances when execution fails after buying power was reserved.verified
- Trade Republic targets instrument search and recommendation returning in under 40 milliseconds, illustrating the latency-budget discipline applied to customer-facing paths.verified
- A brokerage lifecycle splits validation, risk, routing, execution, clearing, settlement, and custody into distinct stages because each is owned by a different legal or operational entity and each can fail independently.internal reasoning
Cited sources
- How to Pass the Trade Republic Software Engineer Interview (JobMentis) · JobMentis (interview outcome database)
- PostgreSQL + Outbox Pattern Revamped Part 1: Incidents and a new design pattern · Trade Republic Engineering (Sadeq Dousti)
- Finding your next investment in less than 40 milliseconds · Trade Republic Engineering