Domain Contracts for Trade Reconciliation

Medium · Software Engineering Fundamentals · Software Engineer · Technical Screen

Prompt

Architect the ingestion layer, domain types, and public API contract for a software library that pairs corresponding buy-side and sell-side trade executions across feeds and surfaces unmatched discrepancies ("breaks").

Rather than hard-coding one file format or one desk's matching heuristic, first identify the domain ambiguities that must be resolved and turned into explicit contract parameters before writing matching code — including which attributes establish trade compatibility, whether executions pair strictly one-for-one or allocate quantity across split fills, how clock units, timezones, and allowable timestamp skew behave, which global pairing objective and tie-breaker govern multi-candidate windows, whether data arrives in bounded batches or continuous streams, and how malformed or duplicate records are handled. Then show how those decisions define clean object boundaries between parsing, matching, and break reporting.

Scope & Expectations

  • Enumerate the clarifying questions needed to turn an underspecified reconciliation request into an explicit, auditable policy contract.
  • Define clean module boundaries separating raw text parsing and validation, exact financial and timestamp domain types, pure matching logic, and structured break outputs.
  • Explain how timestamp skew tolerances, split-fill quantity allocation, and multi-candidate tie-breaking shape pairing semantics and algorithm choice.
  • Specify how corrupt input lines, duplicate deliveries, and delayed records are tracked so operations teams get deterministic, traceable results.

Step-by-step walkthrough

  1. Clarify what "reconciled" means and freeze it in a policy

    Trade reconciliation compares two records of trading activity — for example, an internal execution log and an exchange confirmation feed — pairs up buy/sell or internal/external records that describe the same trade, and flags anything left over as a break (an unexplained discrepancy requiring investigation).

    Before writing matching code, every ambiguity in the prompt must become an explicit field of the library's contract, because each answer changes the data structures and algorithm:

    Ambiguity to resolve up front Contract field Why it changes the implementation
    Compatibility attributes across buy/sell sides Exact match key, e.g. (instrument, quantity, price) across opposite sides Determines how records are partitioned before time comparison
    Strictly 1-to-1 pairing vs partial fills allocation mode (ONE_TO_ONE, BY_ORDER_ID, FIFO_SPLIT) One-to-one is bipartite pair matching; splits are quantity allocation
    Clock resolution, UTC offset, and skew window UTC integer nanoseconds + inclusive tolerance_ns Real system clocks drift slightly, so == almost always fails
    Multi-candidate windows and tie resolution objective + deterministic tie-breaker (ts_ns, record_id) "Closest gap first" can create avoidable breaks; unsorted ties depend on file order
    Bounded batch snapshot vs live event stream Finality / watermark rule Streaming breaks stay provisional until late records can no longer arrive

    Rather than hard-coding one desk's rules inside the matcher, package these decisions into an immutable (frozen=True) MatchPolicy object owned by the caller and stamp policy.version onto every result and break:

    from dataclasses import dataclass
    
    
    @dataclass(frozen=True)
    class MatchPolicy:
        version: str                     # stamped onto every result and break for auditability
        tolerance_ns: int = 500_000_000  # inclusive window: abs(t_buy - t_sell) <= 500 ms
        objective: str = "MAX_PAIRS"     # e.g. "MAX_PAIRS" or "MAX_PAIRS_MIN_TOTAL_GAP"
        allocation: str = "ONE_TO_ONE"   # or "BY_ORDER_ID", "FIFO_SPLIT" when fills split
        strict_parse: bool = False       # True: abort run on first malformed row
        allow_non_positive_price: bool = False  # True for spreads or negative-price futures
    

    To make the code concrete below, we illustrate one clear contract — one-to-one matching of BUY vs SELL sharing exact (instrument, quantity, price) within tolerance_ns — and show where alternative policy choices plug in.

  2. Separate parsing, matching, and reporting at clean boundaries

    Split the library into three single-responsibility boundaries so raw text formatting, matching math, and break reporting never tangle together:

     raw rows (CSV / FIX)                     MatchPolicy (caller-owned, immutable)
              |                                            |
              v                                            v
     +------------------+   valid Trade list    +---------------------+
     |      Parser      | --------------------> |       Matcher       |
     | strings -> types |                       |    pure function    |
     +------------------+                       +---------------------+
              |                                            |
              | Reject(source, line_no, raw, reason)       | matches + breaks
              +--------------------+-----------------------+
                                   v
                         ReconciliationResult
              (matches, breaks, rejects, duplicate_count, policy_version)
    
    • Parser owns raw strings and schema validation. It converts each input line into either a typed Trade or a structured Reject recording the source name, line number, raw payload, and exact failure reason. Malformed data never reaches the matcher and is never dropped silently.
    • Matcher is a pure function (trades, policy) -> (matches, breaks). A pure function reads no files, checks no wall-clock time, and mutates no global state, so feeding the same trades and policy always produces the exact same output.
    • ReconciliationResult owns auditability. Callers inspect matched pairs, actionable breaks, and parse rejects in one place alongside policy.version.
  3. Parse strings into exact domain types (never floats or naive times)

    Financial reconciliation relies on exact equality for match keys and exact arithmetic for timestamps, so the parser must enforce three strict conversions at the boundary:

    1. Amounts as Decimal from the raw string, never float. Binary floating point cannot represent 0.10 exactly: 100.1 * 3 evaluates to 300.29999999999995, whereas Decimal("100.10") * Decimal("3") is Decimal("300.30"). Also check value.is_finite(), because Decimal("NaN") and Decimal("Infinity") parse without raising InvalidOperation and would break sorting or hashing later.
    2. Timestamps as integer nanoseconds since the UTC epoch. Reject naive timestamps lacking a UTC offset (Z or +HH:MM / -HH:MM) unless the policy explicitly supplies the feed's timezone. Note a subtle Python pitfall: datetime.fromisoformat stores only microseconds (10^-6 s) and silently truncates nanosecond digits in strings like "2026-03-02T14:30:00.123456789+00:00"! Splitting the fractional seconds before fromisoformat and padding to 9 digits preserves exact 1-nanosecond precision.
    3. Domain invariants. Normalize "B", "BUY", "buy" into a Side enum, require quantity > 0, and check price > 0 unless policy.allow_non_positive_price is enabled (needed for calendar spreads or contracts like WTI crude oil futures, which settled below zero in April 2020).
    import re
    from dataclasses import dataclass
    from datetime import datetime, timezone
    from decimal import Decimal, InvalidOperation
    from enum import Enum
    
    
    class Side(Enum):
        BUY = "BUY"
        SELL = "SELL"
    
    
    SIDE_ALIASES = {"B": Side.BUY, "BUY": Side.BUY, "S": Side.SELL, "SELL": Side.SELL}
    EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
    ISO_TS_RE = re.compile(
        r"^(\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$"
    )
    
    
    @dataclass(frozen=True)
    class Trade:
        record_id: str
        source: str
        line_no: int
        side: Side
        instrument: str
        quantity: Decimal
        price: Decimal
        ts_ns: int  # exact UTC nanoseconds since 1970-01-01T00:00:00Z
    
    
    @dataclass(frozen=True)
    class Reject:
        source: str
        line_no: int
        raw: str
        reason: str
    
    
    def parse_decimal(text: str, field_name: str) -> Decimal:
        try:
            value = Decimal(text.strip())
        except InvalidOperation:
            raise ValueError(f"{field_name}: invalid decimal {text!r}")
        if not value.is_finite():
            raise ValueError(f"{field_name}: non-finite decimal {text!r}")
        return value
    
    
    def parse_timestamp_ns(text: str) -> int:
        match = ISO_TS_RE.match(text.strip())
        if match is None:
            raise ValueError(f"timestamp must be ISO-8601 with UTC offset and <=9 fractional digits: {text!r}")
        whole_part, frac_part, offset_part = match.groups()
        if offset_part == "Z":
            offset_part = "+00:00"
        frac_ns = int((frac_part or "").ljust(9, "0"))
        moment = datetime.fromisoformat(whole_part + offset_part)
        delta = moment - EPOCH
        whole_seconds = delta.days * 86_400 + delta.seconds
        return whole_seconds * 1_000_000_000 + frac_ns
    
    
    def parse_csv_row(source: str, line_no: int, raw: str, policy: MatchPolicy):
        fields = raw.split(",")  # use csv.reader if fields may contain quoted commas
        if len(fields) != 6:
            return Reject(source, line_no, raw, f"expected 6 fields, got {len(fields)}")
        record_id, side_raw, instrument, qty_raw, price_raw, ts_raw = fields
    
        side = SIDE_ALIASES.get(side_raw.strip().upper())
        if side is None:
            return Reject(source, line_no, raw, f"unknown side {side_raw!r}")
    
        try:
            quantity = parse_decimal(qty_raw, "quantity")
            price = parse_decimal(price_raw, "price")
            ts_ns = parse_timestamp_ns(ts_raw)
        except ValueError as exc:
            return Reject(source, line_no, raw, str(exc))
    
        if quantity <= 0:
            return Reject(source, line_no, raw, "quantity must be positive")
        if not policy.allow_non_positive_price and price <= 0:
            return Reject(source, line_no, raw, "price must be positive")
    
        return Trade(
            record_id=record_id.strip(),
            source=source,
            line_no=line_no,
            side=side,
            instrument=instrument.strip(),
            quantity=quantity,
            price=price,
            ts_ns=ts_ns,
        )
    
  4. Model timestamp tolerance as a sliding window, not buckets

    Why can't two feeds require t_buy == t_sell? Independent machines suffer from clock skew (tiny offsets between hardware clocks), stamp at different points in the trade lifecycle (gateway receipt vs matching-engine fill), and log at different resolutions (14:30:00.250 ms vs 14:30:00.250431 us). Instead, the contract defines an inclusive tolerance window abs(t_buy - t_sell) <= tolerance_ns:

    tolerance = 500 ms (500,000,000 ns)
    
      BUY  B1 at 14:30:00.200
      SELL S1 at 14:30:00.650  -> |200 - 650| = 450 ms <= 500 ms  (eligible)
      SELL S2 at 14:30:00.750  -> |200 - 750| = 550 ms >  500 ms  (too far -> ineligible)
    

    Two properties of a tolerance window rule out naive hashing or rounding:

    • Proximity is not transitive. Under a 500 ms window, 0 ms is within 500 ms of 400 ms, and 400 ms is within 500 ms of 800 ms, yet 0 ms and 800 ms are 800 ms apart and cannot match. Thus timestamps cannot be partitioned into equivalence classes.
    • Rounding into fixed time buckets fails at every boundary. Truncating to whole seconds puts 14:30:00.999 and 14:30:01.001 (2 ms apart!) into different buckets so they miss each other, while putting 14:30:01.001 and 14:30:01.998 (997 ms apart!) into the same bucket.

    The clean approach partitions records by their exact key (instrument, quantity, price) using a hash map, then sorts each bucket's buys and sells by time.

  5. Resolve multiple eligible candidates with an explicit objective and tie-breaker

    Once a tolerance window can cover multiple candidates, a tempting heuristic like "pair the smallest timestamp gap first" can actually manufacture unnecessary breaks! Watch what happens on four trades sharing the same instrument, quantity, and price under tolerance = 500 ms:

    Buys:   A1 at    0 ms,   A2 at  700 ms
    Sells:  B2 at -400 ms,   B1 at  300 ms
    
    Eligible pairs (|t_buy - t_sell| <= 500 ms):
      (A1, B1) gap 300 ms
      (A1, B2) gap 400 ms
      (A2, B1) gap 400 ms
    
    Naive "closest gap first":
      Picks (A1, B1) [300 ms], leaving A2 (700 ms) and B2 (-400 ms) 1100 ms apart -> 1 match, 2 breaks!
    
    Maximum-pairs objective:
      Picks (A1, B2) [400 ms] and (A2, B1) [400 ms]                              -> 2 matches, 0 breaks!
    

    For one-to-one matching inside an exact key group, a two-pointer scan over lists sorted by (ts_ns, record_id) provably achieves the maximum number of matched pairs in O(n log n) time: - Compare the earliest remaining buy buys[i] and earliest remaining sell sells[j]. - If abs(buys[i].ts_ns - sells[j].ts_ns) <= tolerance_ns, pair them immediately and advance both pointers (if an optimal matching paired buys[i] with a later sell sells[j'] and sells[j] with a later buy buys[i'], then buys[i'] and sells[j'] sit chronologically between those valid endpoints and are also within tolerance_ns, so swapping never loses a match). - Otherwise, the earlier record is already more than tolerance_ns before the earliest remaining partner on the opposite side — and therefore even further from every subsequent one — so recording it as unmatched loses zero possible matches.

    Note that in Python, Decimal("187.250") == Decimal("187.25") and hash(Decimal("187.250")) == hash(Decimal("187.25")), so trailing zeros in different feeds still land in the exact same dictionary bucket:

    def canonical_sort_key(trade: Trade):
        return (trade.ts_ns, trade.record_id)
    
    
    def match_one_key(buys, sells, tolerance_ns: int):
        """Maximize one-to-one matched pairs within a single exact-key bucket."""
        sorted_buys = sorted(buys, key=canonical_sort_key)
        sorted_sells = sorted(sells, key=canonical_sort_key)
        matches = []
        unmatched = []
    
        i = 0
        j = 0
        while i < len(sorted_buys) and j < len(sorted_sells):
            gap_ns = sorted_buys[i].ts_ns - sorted_sells[j].ts_ns
            if abs(gap_ns) <= tolerance_ns:
                matches.append((sorted_buys[i], sorted_sells[j]))
                i += 1
                j += 1
            elif gap_ns < 0:
                # sorted_buys[i] is too early for sorted_sells[j] and every later sell.
                unmatched.append(sorted_buys[i])
                i += 1
            else:
                # sorted_sells[j] is too early for sorted_buys[i] and every later buy.
                unmatched.append(sorted_sells[j])
                j += 1
    
        unmatched.extend(sorted_buys[i:])
        unmatched.extend(sorted_sells[j:])
        return matches, unmatched
    
    
    def reconcile_one_to_one(trades, policy: MatchPolicy):
        buckets = {}
        for trade in trades:
            key = (trade.instrument, trade.quantity, trade.price)
            if key not in buckets:
                buckets[key] = ([], [])
            if trade.side is Side.BUY:
                buckets[key][0].append(trade)
            else:
                buckets[key][1].append(trade)
    
        all_matches = []
        all_unmatched = []
        for key in sorted(buckets):
            buys, sells = buckets[key]
            matched, unmatched = match_one_key(buys, sells, policy.tolerance_ns)
            all_matches.extend(matched)
            all_unmatched.extend(unmatched)
        return all_matches, all_unmatched
    

    (If a desk instead asks for "maximum pairs, and among those minimum total timestamp gap," the policy switches the per-key solver from two pointers to dynamic programming over the sorted lists in O(n * m) time.)

  6. Handle partial fills as deterministic quantity allocation

    A partial fill occurs when a single order (say BUY 100 shares at $50.00) is executed on the venue in several smaller child slices (SELL 60, SELL 30, SELL 10 at $50.00). Quantity is then no longer part of the exact match key — only (instrument, price) is — and guessing which subset of fills adds up to 100 is both ambiguous and computationally intractable:

    Internal record:  BUY 100 @ 50.00
    Venue fills:      SELL 60, SELL 30, SELL 40, SELL 10 @ 50.00
    
    Both {60, 40} and {60, 30, 10} sum to 100 -> which sell is the real 40-share break?
    

    In general, searching for an exact-sum subset is the NP-complete subset-sum problem (requiring exponential search in the worst case). A reliable contract avoids subset guessing and chooses one deterministic rule in MatchPolicy.allocation:

    1. Aggregate by shared parent order_id (BY_ORDER_ID): When both feeds carry a common order or execution-group identifier, sum fill quantities per (order_id, instrument, price) on each side first and compare totals.
    2. Chronological FIFO slice allocation (FIFO_SPLIT): Sort buys and sells by (ts_ns, record_id) and consume open quantity from the earliest eligible partner within tolerance_ns. Against SELL 60, 30, 40, BUY 100 allocates 60 from the first, 30 from the second, and 10 from the third, leaving an explicit QUANTITY_RESIDUAL break of 30 on the third sell.
    3. No splitting (ONE_TO_ONE): Emit quantity mismatches straight to operations as breaks rather than fabricating synthetic splits.
  7. Design traceable breaks, idempotency, and late-arrival amendments

    An operations engineer reading a break report should never have to re-query raw logs by hand to learn why a trade failed to match. Each Break carries its provenance, nearest rejected candidates, and policy version:

    @dataclass(frozen=True)
    class Break:
        kind: str                 # "UNMATCHED", "QUANTITY_RESIDUAL", "DUPLICATE_CONFLICT"
        record_ids: tuple         # e.g. ("B1",) or ("B7", "B7") on conflicting duplicates
        locations: tuple          # ((source, line_no), ...) for instant file lookup
        unmatched_qty: Decimal    # full trade quantity, or leftover slice under FIFO_SPLIT
        nearest_candidates: tuple # e.g. (("S2", "gap 550 ms > tolerance 500 ms"),)
        policy_version: str
    

    Finally, the contract must define how duplicates and late records interact with already-reported breaks:

    • Idempotent exact duplicates: If (source, record_id) arrives twice with identical fields (for instance, a retried file upload), drop the second copy and increment duplicate_count so reprocessing is idempotent (running the same data twice yields the exact same result). If the same record_id arrives with different fields, emit a DUPLICATE_CONFLICT break rather than guessing which version is right.
    • Late arrivals in batch vs streaming: Inside a key bucket, a single late trade can shift downstream pairs! Suppose buys at 0, 400, 800 ms initially match sells at 200, 600, 1000 ms (0 breaks under 500 ms tolerance). If a late sell arrives at -100 ms, a full re-run pairs (0, -100), (400, 200), (800, 600) and turns the 1000 ms sell into a brand-new break. Therefore, either freeze published matches (matching late arrivals only against open breaks) or emit explicit versioned amendment events (break #42 resolved by S9, new break #51 on S_1000), and in streaming mode hold breaks provisional until an event-time watermark passes ts_ns + tolerance_ns + allowed_lateness_ns.

Intuition & how it works

Think of reconciling your monthly credit-card statement against a shoebox of paper receipts: a coffee receipt stamped 08:14:02 matches the bank line posted at 08:14:05 for the exact same $4.50, a $100 online order shipped in two boxes billed as $60 and $40, and one torn receipt cannot be read at all. Trade reconciliation (comparing two independent logs of trades to pair records describing the same economic transaction and surface any leftover or mismatched record as a break) requires locking down those rules before coding. We capture every rule in an immutable caller-owned MatchPolicy and split the library into three clean boundaries: a parser that turns raw text into exact domain values (Decimal prices/quantities and integer UTC nanoseconds) or structured Reject objects, a pure matcher (a function whose output depends solely on (trades, policy) with zero I/O, clock reads, or hidden state), and a result object carrying self-explaining breaks.

Why do quick-and-dirty implementations fail in production? Parsing prices into binary float (100.1 * 3 == 300.29999999999995), requiring exact timestamp equality ==, or rounding timestamps into whole-second buckets manufactures false breaks on completely valid trades. Equally dangerous, greedily pairing the smallest timestamp gap first without a stated objective can strand matchable trades, and silently dropping malformed lines or overwriting published breaks hides real financial discrepancies from operations teams.

Here is a concrete four-trade trace within one exact (instrument, Decimal("100"), Decimal("50.25")) bucket under a 500 ms tolerance, showing why sorting by (ts_ns, record_id) and scanning with two pointers beats naive closest-gap pairing:

Buys:   A1 at    0 ms,   A2 at  700 ms
Sells:  B2 at -400 ms,   B1 at  300 ms

Sorted buys:  [A1 (0 ms),    A2 (700 ms)]
Sorted sells: [B2 (-400 ms), B1 (300 ms)]

Pointer step 1: compare earliest buy A1 (0 ms) vs earliest sell B2 (-400 ms)
                |0 - (-400)| = 400 ms <= 500 ms -> pair (A1, B2)
Pointer step 2: compare next buy A2 (700 ms) vs next sell B1 (300 ms)
                |700 - 300|  = 400 ms <= 500 ms -> pair (A2, B1)

Result: 2 matches, 0 breaks (closest-gap-first would grab (A1, B1) [300 ms] and leave 2 breaks!)

Key points

  • Turn every ambiguity into an explicit MatchPolicy field: Match key fields, one-to-one vs partial fills (a single order executed across several smaller child trades), timestamp tolerance, pairing objective, tie-breaker, and strict vs lenient parsing belong in an immutable configuration object stamped (policy.version) onto every output.
  • Keep parsing, matching, and reporting strictly separated: Only the parser touches raw strings; malformed lines become Reject(source, line_no, raw, reason) records so bad input neither crashes a lenient run nor vanishes silently, while the matcher stays a pure, deterministic function.
  • Use exact representations at the domain boundary: Parse prices and quantities directly from strings into Decimal (checking is_finite()) and parse timestamps with explicit UTC offsets into integer nanoseconds — splitting fractional seconds manually rather than relying on datetime.fromisoformat alone, which silently truncates nanoseconds to microseconds.
  • Treat timestamp tolerance as a non-transitive sliding window: abs(t_buy - t_sell) <= tolerance_ns is neither transitive (0 ms ~ 400 ms and 400 ms ~ 800 ms, yet 0 ms !~ 800 ms) nor compatible with fixed time buckets (00.999 and 01.001 split across whole-second buckets despite a 2 ms gap). Partition by exact key fields in a hash map, then sort by time within each bucket.
  • Pair by a stated objective and canonical tie-breaker: Sorting each side by (ts_ns, record_id) and running a two-pointer scan maximizes one-to-one matched pairs in O(n log n) time independently of input row order; minimizing total time gap as a secondary objective requires dynamic programming (O(n * m)) or assignment algorithms.
  • Treat partial fills as deterministic allocation, not subset search: Searching fill subsets that sum to an order quantity is the NP-complete subset-sum problem (exponential worst-case search and ambiguous when {60, 40} and {60, 30, 10} both sum to 100). Prefer aggregating by a shared order_id or allocating chronologically (FIFO_SPLIT) with explicit residual breaks.
  • Make breaks self-explaining and amendments versioned: Every Break should list record_ids, (source, line_no), leftover quantity, nearest_candidates with rejection reasons (e.g., "S2: gap 550 ms > 500 ms"), and policy_version.

Common mistakes

  • Parsing monetary prices or quantities into float: Binary rounding (0.1 + 0.2 != 0.3) causes exact dictionary lookups and equality checks on (instrument, quantity, price) to miss legitimate counterparts.
  • Accepting naive timestamps without a timezone or truncating nanoseconds: Mixing New York local time with UTC creates multi-hour offsets, and Python's datetime.fromisoformat silently drops digits 7–9 of fractional seconds unless parsed explicitly.
  • Implementing tolerance by rounding timestamps to whole seconds or milliseconds: Two records 2 ms apart straddling .999 and .001 fall into different buckets and become false breaks, while two records 997 ms apart inside the same second falsely match under a 500 ms tolerance.
  • Using "smallest timestamp gap first" without realizing it can reduce match count: As shown in the trace above, grabbing a 300 ms match can block two 400 ms matches and turn 0 breaks into 2 breaks.
  • Letting dictionary/set iteration order or arrival order decide ties: Without sorting by a unique tie-breaker like (ts_ns, record_id), re-running the exact same trades in shuffled order pairs different records and flips which record is reported as the break.
  • Silently discarding malformed lines or overwriting published breaks in place: Audit trails require counted Reject records for bad lines and append-only versioned amendments when late trades resolve or shift earlier matches.

Follow-up questions

  • Why does demanding identical execution timestamps fail across independent trading systems, even with clock synchronization? Separate venues and gateways rarely stamp the exact same nanosecond: hardware clocks exhibit clock skew (small drift between servers), the two feeds record different lifecycle moments (order-gateway receipt vs matching-engine fill confirmation), and serializers emit different fractional precisions (14:30:00.250 vs 14:30:00.250431). Under a 500 ms skew window, a buy at .200 and a sell at .650 (450 ms apart) describe the same execution, whereas == would falsely flag both records as unmatched breaks.
  • How should the library choose pairings when multiple opposite-side trades fall inside the permitted time window? Once a single execution sits within tolerance_ns of several opposite-side candidates, the contract must specify both a global pairing objective and a deterministic tie-breaker. For example, with buys at 0 ms, 700 ms and sells at -400 ms, 300 ms under a 500 ms window, greedy closest-gap pairing picks (0, 300) and leaves 2 breaks, whereas maximizing matched pairs via a two-pointer scan over (ts_ns, record_id)-sorted lists pairs (0, -400) and (700, 300) with 0 breaks. Flagging when a matched trade had multiple eligible partners also helps operations spot genuinely ambiguous bursts.
  • What happens to breaks that have already been emitted if duplicate messages or delayed executions arrive later? Exact duplicates (same (source, record_id) and identical fields) should be deduplicated and counted so file retries remain idempotent (producing the same state when delivered twice), whereas the same record_id with differing fields must raise an explicit DUPLICATE_CONFLICT break. For delayed arrivals, note that re-running two-pointer matching inside a key bucket can cascade: if buys at 0, 400, 800 ms matched sells at 200, 600, 1000 ms (500 ms window) and a delayed sell arrives at -100 ms, re-solving pairs (0, -100), (400, 200), (800, 600) and turns 1000 ms into a new break! To handle this cleanly, either freeze already-published matches and match late arrivals only against open breaks, or hold streaming breaks provisional until an event-time watermark passes ts_ns + tolerance_ns + allowed_lateness_ns and emit explicit versioned amendments (break #42 resolved by S9) afterward rather than mutating historical reports.

Follow-up questions

Similar questions

More Citadel Securities interview questions

All 4 Citadel Securities questions →