Data Model for Time-Versioned Trading Restrictions

Medium · System Design · Data Engineer · Technical Screen

Prompt

Architect the storage schema and serving query layer for a pre-trade compliance platform that enforces trading restrictions across financial instruments—for instance, blocking orders on exchange symbol NVO for accounts domiciled in jurisdiction JP.

Your design must satisfy four core temporal and domain requirements:

  • Inclusive effective windows & backdated entries: Each rule carries an inclusive effective_date and inclusive end_date (or remains open-ended), and legal teams may submit rules whose effective window starts retroactively in the past.
  • Time-versioned instrument master: Issuers rename symbols and undergo corporate events; while identifiers like ISIN generally stay attached to an instrument, exchange tickers change over time and are frequently reassigned to unrelated companies later.
  • Multi-authority precedence: Separate rulemakers (external regulators, exchanges, and internal compliance desks) can attach concurrent, overlapping rules to the same instrument with distinct priority levels.
  • Dual-timeline auditability: Compliance auditors must be able to reconstruct the exact universe state both as valid on a given market date and as recorded in the system at any historical timestamp (valid time versus system time).

Assume roughly 100,000 active instruments, 500+ asynchronous rule edits per day submitted concurrently by separate legal teams, and high-throughput, low-latency read traffic during live order entry.

Scope & Expectations

  • Relational & temporal schema: Define the tables, keys, and temporal intervals for Securities, Restrictions, identifier mappings, and the association table linking rules to instruments.
  • Historical symbol resolution: Show how a query such as "Was symbol NVO restricted on 2023-04-10?" resolves accurately even if NVO was subsequently reassigned to a different company.
  • Order-entry API & conflict resolution: Specify the API contract and query/precedence logic that evaluates trade compliance for a given trade_date and security_id (plus order context), both live and as of a past audit timestamp.
  • Concurrency & low-latency serving: Address safe concurrent rule edits across legal teams and sub-millisecond read serving without stale-cache errors.

Step-by-step walkthrough

  1. Clarify requirements and the two timelines

    This problem is a bitemporal data-modeling design at its core paired with a low-latency order-entry serving layer. Spend the first two minutes defining the two timelines auditors ask about, because the entire schema falls cleanly out of that distinction:

    valid time    The calendar dates a rule or ticker assignment applies in the real world
                  (e.g., "Trading prohibited from 2023-04-01 through 2023-04-30 inclusive").
    system time   The exact UTC window when our database recorded and believed that version
                  (e.g., "Legal entered this retroactive ban on 2023-06-10 at 09:00 UTC").
    

    Functional requirements & assumptions: - Multi-authority restrictions: Regulators, exchanges, and internal legal teams create rules with an effect (BLOCK, WARN, or an ALLOW exemption), a priority, optional scopes (country of the trading account/entity, legal_entity, trade side = BUY | SELL | BOTH), an effective_date, and an inclusive end_date (or open-ended). Rules may be entered retroactively or corrected later without ever erasing prior versions. - Versioned security master: Securities change tickers, undergo mergers/spin-offs, and delist; exchanges reassign old tickers to brand-new companies. Because the same symbol (like NVO) can trade on multiple exchanges simultaneously, ticker lookups take an exchange MIC (Market Identifier Code, such as XNYS for NYSE); if omitted and multiple exchanges match, the API flags the ambiguity instead of guessing. - Live checks & historical audits: Answer "Is this trade compliant right now?" by (sec_id, trade_date, side, account) at order entry, and answer "Was symbol NVO restricted on 2023-04-10—both according to what we know today and according to what we knew on 2023-05-01?"

    Non-functional requirements: - Latency & throughput: ~5,000 order-entry compliance checks/s at market open with < 1 ms in-service latency (< 5 ms end-to-end). - Freshness & safety: Newly approved rules enforce across all check instances within 1–2 seconds. When compliance state cannot be verified, order entry fails closed (holds orders rather than sending unchecked trades to market).

  2. Back-of-the-envelope numbers: rare writes, ultra-fast reads

    1. Security Master & Identifier Map
       Active securities:            100,000
       Identifiers per security:     ~4 (TICKER+MIC, ISIN, CUSIP/SEDOL, FIGI) -> ~400,000 active rows
       Identifier churn (~5%/year):  ~5,000 new rows/year -> < 1,000,000 rows total after 10 years!
    
    2. Restrictions & Join Table
       Rule updates:                 500/day * 250 trading days = 125,000 versions/year (~1 write/min!)
       Targets per rule change:      ~4 on average (1 for single-name rules; hundreds for sanctions lists)
       Target rows over 10 years:    ~500,000/year * 10 = ~5,000,000 rows * ~200 B = ~1.0 GB total
       Currently active rules:       ~20,000 rules covering ~80,000 active (rule, security) pairs
    
    3. Read Path & Audit Log
       Order-entry peak:             ~5,000 checks/s at market open
       In-memory active snapshot:    80,000 pairs * ~100 B (~8 MB) + identifier map (~40 MB) = ~50 MB!
       Order decision audit log:     ~2,000,000 checks/day * ~300 B = ~600 MB/day (partitioned daily)
    

    Three architectural conclusions jump right out of the math: 1. 1 GB of 10-year rule history fits effortlessly in one PostgreSQL database—sharding would be pure overhead. 2. 500 updates/day is ~1 write per minute, so serializing writes through a single monotonic change counter costs nothing and eliminates out-of-order concurrency bugs. 3. The entire active compliance universe is ~50 MB, small enough to live completely in RAM inside every compliance-check server for microsecond lookups!

  3. API contracts for trade checks, ticker resolution, and rule edits

    POST /v1/compliance/check
      { "security":   { "sec_id": 501 }            -- or { "id_type": "TICKER", "id_value": "NVO", "mic": "XNYS" }
        "trade_date": "2023-04-14",
        "side":       "BUY",
        "account_id": "DESK7-JP",                  -- resolves to legal_entity="DESK7", country="JP"
        "as_of":      null }                       -- null = current knowledge; timestamp = historical audit
    -> 200 OK
      { "decision":          "BLOCK",              -- BLOCK | WARN | ALLOW
        "sec_id":            501,
        "winning_rule":      { "restriction_id": 14, "version": 2, "authority": "JFSA", "priority": 100 },
        "matched_rules":     [ ...all matching rule versions for trader/auditor transparency... ],
        "knowledge_version": 884213 }              -- exact monotonic change_id used to make this decision
    -> 409 AMBIGUOUS_IDENTIFIER  (ticker without MIC matched multiple exchanges on trade_date)
    -> 404 UNKNOWN_IDENTIFIER    (identifier was not assigned to any security on trade_date)
    
    GET  /v1/securities/resolve?id_type=TICKER&id_value=NVO&mic=XNYS&on=2023-04-10&as_of=2023-05-01T00:00Z
    GET  /v1/restrictions?sec_id=501&valid_on=2023-04-10&as_of=2023-05-01T00:00Z
    
    POST /v1/restrictions                          -- create newly approved restriction
    PUT  /v1/restrictions/{restriction_id}         -- create version v+1 (amendment, correction, or cancel)
         { "expected_version": 1, "change_kind": "CORRECTION", "reason": "...", ... }
         Idempotency-Key: <uuid>
    -> 200 OK { "restriction_id": 14, "version": 2, "knowledge_version": 884214 }
    -> 409 VERSION_CONFLICT  (another legal team updated version 1 first)
    
    • knowledge_version (change_id) in every check response: The Order Management System (OMS) stores knowledge_version on the order record so an auditor years later can replay the exact database state that approved or blocked that order.
    • expected_version (optimistic concurrency): Requiring the caller's last read version stops two legal teams editing the same rule asynchronously from overwriting each other's changes.
  4. Bitemporal schema: `Securities`, `Identifier Map`, `Restrictions`, and `Targets`

    Every versioned table carries two half-open intervals [from, to)—meaning the start is inclusive (<=) and the end is exclusive (<): - Business users enter inclusive end_dates (like 2023-04-30), which the API stores as valid_to = end_date + 1 day (2023-05-01), or 'infinity' when open-ended. Half-open intervals eliminate +1/-1 off-by-one bugs, allow back-to-back periods [Apr 1, Oct 1) and [Oct 1, infinity) to touch cleanly without overlapping, and work natively with PostgreSQL GiST exclusion constraints (database constraints that reject two rows with the same key if their date ranges overlap). - Explicit CHECK (valid_from < valid_to) and CHECK (sys_from < sys_to) constraints block inverted or empty zero-day ranges (which would otherwise evaluate to 'empty' in PostgreSQL and bypass overlap checks!).

    CREATE EXTENSION IF NOT EXISTS btree_gist;
    
    -- 1. Securities: permanent surrogate key `sec_id` (never changed, never reused)
    CREATE TABLE securities (
        sec_id      BIGINT PRIMARY KEY,
        created_at  TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE security_versions (
        sec_id      BIGINT NOT NULL REFERENCES securities,
        issuer_id   BIGINT NOT NULL,
        name        TEXT   NOT NULL,
        status      TEXT   NOT NULL,                   -- ACTIVE, DELISTED, MERGED
        valid_from  DATE   NOT NULL,
        valid_to    DATE   NOT NULL,                   -- exclusive ('infinity' = open-ended)
        sys_from    TIMESTAMPTZ NOT NULL,
        sys_to      TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
        change_id   BIGINT NOT NULL,
        CHECK (valid_from < valid_to),
        CHECK (sys_from < sys_to)
    );
    
    -- 2. Identifier Map: resolves TICKER+MIC, ISIN, CUSIP, SEDOL, FIGI at any point in time
    CREATE TABLE identifier_map (
        sec_id      BIGINT NOT NULL REFERENCES securities,
        id_type     TEXT   NOT NULL,                   -- TICKER, ISIN, CUSIP, SEDOL, FIGI
        id_value    TEXT   NOT NULL,
        mic         TEXT   NOT NULL DEFAULT '',        -- exchange MIC for tickers; '' for global IDs
        valid_from  DATE   NOT NULL,
        valid_to    DATE   NOT NULL,
        sys_from    TIMESTAMPTZ NOT NULL,
        sys_to      TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
        change_id   BIGINT NOT NULL,
        CHECK (valid_from < valid_to),
        CHECK (sys_from < sys_to),
        -- In current belief, an identifier+exchange can point to at most ONE security on any date
        EXCLUDE USING gist (
            id_type WITH =, id_value WITH =, mic WITH =,
            daterange(valid_from, valid_to, '[)') WITH &&
        ) WHERE (sys_to = 'infinity')
    );
    CREATE INDEX identifier_lookup_idx ON identifier_map (id_type, id_value, mic, valid_from);
    
    -- 3. Authorities & Restrictions (bitemporal rule versions)
    CREATE TABLE authorities (
        authority_id      BIGINT PRIMARY KEY,
        name              TEXT NOT NULL,
        kind              TEXT NOT NULL,               -- REGULATOR, EXCHANGE, INTERNAL
        default_priority  INT  NOT NULL,               -- e.g. Regulator = 100, Internal = 50
        max_priority      INT  NOT NULL                -- caps priority so internal rules cannot beat regulators
    );
    
    CREATE TABLE restrictions (
        restriction_id  BIGINT PRIMARY KEY,
        authority_id    BIGINT NOT NULL REFERENCES authorities,
        external_ref    TEXT,
        created_at      TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE restriction_versions (
        restriction_id  BIGINT  NOT NULL REFERENCES restrictions,
        version         INT     NOT NULL,
        is_active       BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE when a rule is cancelled outright
        effect          TEXT    NOT NULL,              -- BLOCK, WARN, ALLOW
        side            TEXT    NOT NULL,              -- BUY, SELL, BOTH
        scope_country   TEXT,                          -- NULL = all countries
        scope_entity    TEXT,                          -- NULL = all legal entities
        priority        INT     NOT NULL,
        valid_from      DATE    NOT NULL,              -- effective_date
        valid_to        DATE    NOT NULL,              -- end_date + 1 day, or 'infinity'
        sys_from        TIMESTAMPTZ NOT NULL,
        sys_to          TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
        change_id       BIGINT  NOT NULL,
        change_kind     TEXT    NOT NULL,              -- NEW, AMEND, CORRECTION, CANCEL
        reason          TEXT    NOT NULL,
        approved_by     TEXT    NOT NULL,
        PRIMARY KEY (restriction_id, version),
        CHECK (valid_from < valid_to),
        CHECK (sys_from < sys_to)
    );
    CREATE UNIQUE INDEX one_current_rule_ver ON restriction_versions (restriction_id)
        WHERE sys_to = 'infinity';
    
    -- 4. Join Table connecting Restrictions <-> Securities over both timelines
    CREATE TABLE restriction_targets (
        restriction_id  BIGINT NOT NULL REFERENCES restrictions,
        sec_id          BIGINT NOT NULL REFERENCES securities,
        valid_from      DATE   NOT NULL,               -- '-infinity'..'infinity' for fixed-target rules;
        valid_to        DATE   NOT NULL,               -- specific dates when names join/leave a list rule
        sys_from        TIMESTAMPTZ NOT NULL,
        sys_to          TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
        change_id       BIGINT NOT NULL,
        entered_as      TEXT   NOT NULL,               -- audit trail of raw input, e.g. 'TICKER NVO XNYS'
        CHECK (valid_from < valid_to),
        CHECK (sys_from < sys_to),
        EXCLUDE USING gist (
            restriction_id WITH =, sec_id WITH =,
            daterange(valid_from, valid_to, '[)') WITH &&
        ) WHERE (sys_to = 'infinity')
    );
    CREATE INDEX targets_current_idx ON restriction_targets (sec_id, valid_from) WHERE sys_to = 'infinity';
    CREATE INDEX targets_history_idx ON restriction_targets (sec_id, sys_from);
    
    -- 5. Single-row serializer + append-only change outbox for cache tailing
    CREATE TABLE change_counter (
        last_change_id  BIGINT      NOT NULL,
        last_committed  TIMESTAMPTZ NOT NULL
    );
    
    CREATE TABLE changes (
        change_id     BIGINT PRIMARY KEY,
        committed_at  TIMESTAMPTZ NOT NULL,
        kind          TEXT  NOT NULL,                  -- RESTRICTION, TARGETS, IDENTIFIER, SECURITY
        payload       JSONB NOT NULL
    );
    

    Notice a crucial schema detail on restriction_targets: - For a standard rule targeting fixed securities ("Block NVO from Apr 1 to Jun 30"), store rt.valid_from = '-infinity', rt.valid_to = 'infinity' on restriction_targets and keep [2023-04-01, 2023-07-01) on restriction_versions. That way, if Legal later extends the rule's end_date to September 30 in restriction_versions, 1 row changes and the extended dates are never silently clipped by stale dates on restriction_targets! - For a rolling list rule ("EU Sanctions List", where rule rv is open-ended [2020-01-01, infinity) and individual securities join or leave on different days), restriction_targets sets [rt.valid_from, rt.valid_to) per security. Taking the intersection of rv and rt in our join handles both patterns seamlessly!

  5. High-level architecture

       Legal / Compliance UI (4-eyes approval)         Security Master Vendor Feeds
                         |                                           |
                         v                                           v
             +-----------------------+                   +-----------------------+
             | Rule Writer Service   |                   | Master Loader Service |
             | validates, resolves   |                   | stages & validates    |
             | tickers as-of date    |                   | corporate actions     |
             +-----------+-----------+                   +-----------+-----------+
                         |     serialized single-tx write (`change_counter` + `changes`)
                         +---------------------+---------------------+
                                               v
             +-------------------------------------------------------------------+
             | PostgreSQL Primary (+ Quorum Sync Standby, + Async Read Replica)  |
             | securities, identifier_map, restrictions, restriction_versions,   |
             | restriction_targets, change_counter, changes                      |
             +-----------------+-----------------------------------+-------------+
                               | polls `changes WHERE change_id>K` | SQL as-of reads
                               | every 100 ms                      v
                               v                       +-------------------------+
             +---------------------------------+       | Audit & Impact Service  |
             | Compliance Check Service (3+ x) |       | historical as_of audits |
             | ~50 MB in-RAM bitemporal index  |       | & retroactive reports   |
             +-----------------+---------------+       +-------------------------+
                               ^
                               | POST /v1/compliance/check (< 1 ms)
                        Order Management System (OMS) ---> stores decision + knowledge_version
                               |
                               v
                   Append-only Decision Log (partitioned daily)
    
  6. Deep dive 1: valid time vs. system time, retroactive rules, and safe writes

    Two questions look nearly identical in English yet have opposite legal answers: 1. "Was security 501 restricted on 2023-04-10 (given everything we know today)?" — checks valid time under current system time (sys_to = 'infinity'). 2. "When we approved order #418 on 2023-04-10, did our system know security 501 was restricted?" — checks valid time 2023-04-10 under historical system time 2023-04-10T14:30Z.

    Trace both a retroactive rule and a retroactive correction in restriction_versions:

    Case A — Retroactive ban R19 entered on Jun 10 covering Apr 1..Apr 30 inclusive:
      rule  ver  is_active  valid_from  valid_to (excl)  sys_from          sys_to
      R19   1    TRUE       2023-04-01  2023-05-01       2023-06-10 09:00  infinity
      -> Query for 2023-04-10 AS OF 2023-05-01: no row has sys_from <= May 1 -> ALLOW (trade was lawful then!)
      -> Query for 2023-04-10 AS OF TODAY:      R19 v1 matches               -> BLOCK (flagged for retro review)
    
    Case B — Error fix on R14 (entered with end_date Jun 30 by mistake; fixed on Jul 5 to May 31):
      rule  ver  is_active  valid_from  valid_to (excl)  sys_from          sys_to            change_kind
      R14   1    TRUE       2023-02-01  2023-07-01       2023-01-28 09:00  2023-07-05 14:00  NEW
      R14   2    TRUE       2023-02-01  2023-06-01       2023-07-05 14:00  infinity          CORRECTION
      -> Query for 2023-06-15 AS OF 2023-06-20: v1 was current -> BLOCK (explains why June order was rejected)
      -> Query for 2023-06-15 AS OF TODAY:      v2 is current  -> ALLOW (proves June block was an entry error)
    
    • Historical as-of predicate: Every bitemporal table uses valid_from <= :d AND :d < valid_to AND sys_from <= :t AND :t < sys_to. (For current-knowledge queries, write sys_to = 'infinity' directly instead of passing :t = 'infinity', both because 'infinity' < 'infinity' is FALSE in SQL and so PostgreSQL uses the partial indexes WHERE sys_to = 'infinity'!)
    • Atomic serialized write transaction: In PostgreSQL, now() returns transaction start time rather than commit order, and SERIAL sequences can commit out of order. At ~1 write/minute, locking the single row in change_counter makes change ordering trivial and gap-free:
    BEGIN;
    SELECT last_change_id, last_committed FROM change_counter FOR UPDATE;
    -- Compute :change_id = last_change_id + 1
    -- Compute :now = GREATEST(clock_timestamp(), last_committed + interval '1 microsecond')
    
    UPDATE restriction_versions
       SET sys_to = :now
     WHERE restriction_id = 14 AND version = :expected_version AND sys_to = 'infinity';
    -- If 0 rows updated -> ROLLBACK and return 409 VERSION_CONFLICT!
    
    INSERT INTO restriction_versions
      (restriction_id, version, is_active, effect, side, scope_country, scope_entity,
       priority, valid_from, valid_to, sys_from, change_id, change_kind, reason, approved_by)
    VALUES
      (14, :expected_version + 1, TRUE, 'BLOCK', 'BOTH', 'JP', NULL,
       100, '2023-02-01', '2023-06-01', :now, :change_id, 'CORRECTION', :reason, :approver);
    
    UPDATE change_counter SET last_change_id = :change_id, last_committed = :now;
    INSERT INTO changes (change_id, committed_at, kind, payload)
    VALUES (:change_id, :now, 'RESTRICTION', :payload_json);
    COMMIT;
    
  7. Deep dive 2: "ticker at time" resolution across renames and ticker reuse

    Suppose Issuer Alpha (sec_id = 501) traded on NYSE (XNYS) under symbol NVO through 2023-08-31, renamed its symbol to NVX on 2023-09-01, and unrelated Issuer Beta (sec_id = 804) took over symbol NVO on 2024-03-01:

    sec_id  id_type  id_value  mic     valid_from  valid_to    company
    ------  -------  --------  ------  ----------  ----------  -------------------------------
    501     TICKER   NVO       XNYS    2016-05-02  2023-09-01  Issuer Alpha (old symbol)
    501     TICKER   NVX       XNYS    2023-09-01  infinity    Issuer Alpha (renamed to NVX)
    804     TICKER   NVO       XNYS    2024-03-01  infinity    Issuer Beta (reused NVO in 2024!)
    501     ISIN     US000501  ''      2016-05-02  infinity    Issuer Alpha (stable across rename)
    

    If restrictions were keyed by symbol NVO, a 2023 ban on Issuer Alpha would falsely block innocent Issuer Beta today while letting Issuer Alpha trade freely under NVX! With surrogate sec_id + identifier_map, answering "Was symbol NVO restricted on 2023-04-10 (as known at :t)?" is a clean two-step resolution:

    -- Step 1: Resolve ('TICKER', 'NVO', 'XNYS') on 2023-04-10 as known at :t -> returns sec_id = 501
    SELECT sec_id
      FROM identifier_map
     WHERE id_type = 'TICKER' AND id_value = 'NVO' AND mic = 'XNYS'
       AND valid_from <= DATE '2023-04-10' AND DATE '2023-04-10' < valid_to
       AND sys_from   <= :t                AND :t                < sys_to;
    -- Step 2: Run the compliance check query below for sec_id = 501 on 2023-04-10 at :t
    

    Two critical safeguards on rule entry and corporate actions: - Resolve tickers as of effective_date at rule entry: When Legal types "Block NVO starting 2023-02-01" into the UI today, the Rule Writer resolves NVO as of 2023-02-01 (finding Issuer Alpha, sec_id = 501, not Issuer Beta!), displays the resolved company name and ISIN for human confirmation, stores sec_id = 501, and preserves 'TICKER NVO XNYS' in entered_as. - Corporate actions trigger legal review, never blind auto-propagation: sec_id represents the instrument (so all exchange listings sharing an issue map to one sec_id). When a merger or spin-off creates a new successor sec_id, the Master Loader records lineage (parent_sec_id, child_sec_id) and opens a high-priority Compliance Review ticket—because whether a restriction carries over to an acquirer or spun-off company is a legal judgment, not an automated database rule.

  8. Deep dive 3: overlapping rules, priority resolution, and microsecond in-memory serving

    1. Querying and resolving overlapping rules: Multiple authorities can restrict sec_id = 501 simultaneously. Fetch all active matching versions at (:d, :t):

    SELECT rv.restriction_id, rv.version, rv.effect, rv.priority, a.name AS authority
      FROM restriction_targets rt
      JOIN restriction_versions rv ON rv.restriction_id = rt.restriction_id
      JOIN restrictions r          ON r.restriction_id  = rt.restriction_id
      JOIN authorities a           ON a.authority_id    = r.authority_id
     WHERE rt.sec_id = :sec_id
       AND rt.valid_from <= :d AND :d < rt.valid_to
       AND rt.sys_from   <= :t AND :t < rt.sys_to
       AND rv.is_active = TRUE
       AND rv.valid_from <= :d AND :d < rv.valid_to
       AND rv.sys_from   <= :t AND :t < rv.sys_to
       AND rv.side IN (:side, 'BOTH')
       AND (rv.scope_country IS NULL OR rv.scope_country = :country)
       AND (rv.scope_entity  IS NULL OR rv.scope_entity  = :entity);
    

    Combine overlapping rules deterministically: (1) highest priority wins; (2) ties on priority pick the strictest effect (BLOCK > WARN > ALLOW); (3) remaining ties pick the lowest restriction_id. Why priority before restrictiveness? Because compliance occasionally grants a specific fund an approved ALLOW exemption (priority = 60) over a broad internal BLOCK/WARN (priority = 50)—while authorities.max_priority caps internal teams at 60 so no internal exemption can ever override a priority = 100 regulatory BLOCK!

    EFFECT_STRICTNESS = {"ALLOW": 0, "WARN": 1, "BLOCK": 2}
    
    
    def resolve_decision(matched_rules):
        """Choose the winning compliance decision from all matching rule versions.
    
        matched_rules: list of dicts with keys restriction_id, version, effect, priority.
        Returns (decision_effect, winning_rule_dict_or_None).
        """
        if not matched_rules:
            return "ALLOW", None
    
        # Step 1: Highest authority/rule priority wins (e.g., Regulator 100 beats Internal 60)
        highest_priority = max(rule["priority"] for rule in matched_rules)
    
        winning_rule = None
        for rule in matched_rules:
            if rule["priority"] != highest_priority:
                continue
            if winning_rule is None:
                winning_rule = rule
                continue
    
            # Step 2: Within equal priority, fail safe by choosing BLOCK > WARN > ALLOW
            candidate_rank = EFFECT_STRICTNESS[rule["effect"]]
            winner_rank = EFFECT_STRICTNESS[winning_rule["effect"]]
            if candidate_rank > winner_rank:
                winning_rule = rule
            # Step 3: Deterministic tie-breaker on lowest restriction_id for reproducible audits
            elif candidate_rank == winner_rank and rule["restriction_id"] < winning_rule["restriction_id"]:
                winning_rule = rule
    
        return winning_rule["effect"], winning_rule
    
    Example on sec_id = 501, trade_date = 2023-04-14:
      R14  JFSA Regulator    BLOCK   priority 100   scope_country = 'JP'
      R21  Internal Policy   WARN    priority 50    scope = everywhere
      R29  Internal Legal    ALLOW   priority 60    scope_entity  = 'DESK4' (written exemption)
    
      Order from DESK7 in JP -> matches [R14, R21] -> max priority 100 -> BLOCK (R14 wins)
      Order from DESK4 in US -> matches [R21, R29] -> max priority 60  -> ALLOW (R29 exemption beats R21)
      Order from DESK7 in US -> matches [R21]      -> max priority 50  -> WARN  (R21 wins)
    

    2. Serving 5,000 checks/s in < 1 ms without stale-cache bugs: Cache the bitemporal rows, NEVER boolean "is restricted today" answers! - On startup, each Check Service instance opens one REPEATABLE READ transaction, reads K = last_change_id, and loads all sys_to = 'infinity' rows (~50 MB total) into in-memory hash maps keyed by sec_id and (id_type, id_value, mic). - Every 100 ms, the instance polls SELECT * FROM changes WHERE change_id > K ORDER BY change_id, applies deltas in memory, and advances K. If a gap in change_id ever appears, it drops the index and reloads a clean snapshot. - Because the in-memory entries retain their full [valid_from, valid_to) ranges, midnight date rollovers, future-dated rules, and retroactive edits require zero TTL cache invalidation—microsecond lookups automatically evaluate against the order's trade_date and stamp knowledge_version = K! - 2-second freshness guard: Each 100 ms poll confirms database liveness. Any instance that cannot verify K == db_latest_change_id within 2 s marks itself unhealthy so the OMS routes to healthy peers; urgent bans wait (~100–200 ms) until all active instances report K >= new_change_id before showing "Enforced" in the UI.

  9. Failure handling and trade-off summary

    Failure Scenario                    System Behavior
    ----------------------------------  ------------------------------------------------------------------
    Check instance loses DB link        2 s freshness guard pulls instance out of rotation; peers serve
    All check instances unreachable     OMS fails closed: holds orders in queue, never sends unchecked
    DB primary crashes                  Promote quorum sync standby (RPO = 0). Confirmed cluster-wide DB
                                        failover may optionally allow a compliance-signed 60 s read-only
                                        grace window (since zero new rules can commit while primary is down),
                                        whereas a single partitioned check node always fails closed at 2 s
    Concurrent rule edit by 2 teams     `expected_version` mismatch returns 409 VERSION_CONFLICT
    Corrupt vendor security-master load Staged first; GiST overlap + row-count delta checks reject atomically
    Server wall-clock skew backward     `sys_from = GREATEST(clock_timestamp(), last_committed + 1 us)`
                                        under `change_counter` lock keeps `sys_from` strictly monotonic
    

    Key trade-offs summarized: - Bitemporal tables vs. current-state table + audit log: Four timestamp/date columns per table and close-then-insert writes let any historical audit run as a single declarative SQL query instead of error-prone log replay. - Surrogate sec_id + identifier_map vs. natural ticker/ISIN keys: Isolates rules from ticker reuse and symbol renames, trading off an explicit date-aware resolution step. - Half-open [valid_from, valid_to) in storage vs. inclusive dates: Eliminates off-by-one overlap bugs and unlocks PostgreSQL GiST range constraints while translating cleanly to inclusive end_dates at the API boundary. - Serialized writer + tailed ~50 MB in-RAM row index vs. Redis TTL boolean cache: Easily absorbs ~1 write/minute while delivering microsecond order-entry checks that never serve stale answers across midnight or retroactive rule updates.

Intuition & how it works

Think of compliance restrictions for securities like an aviation no-fly-zone ledger maintained for air traffic controllers and flight auditors:

  • Every flight clearance check happens right before takeoff (order entry, ~5,000 checks/s needing < 1 ms latency), while aviation authorities and internal safety teams update ~500 notices per day (~1 change per minute).
  • Crucially, auditors ask two different time questions: "Was airspace NVO restricted on April 10?" (valid time, when the rule applied in the real world) and "When our controller cleared flight #418 on April 10, had the notice actually arrived on our desk yet?" (system time, when our database recorded that version). Tracking both intervals [valid_from, valid_to) and [sys_from, sys_to) on every record—and closing sys_to + inserting a new version instead of overwriting rows—is called a bitemporal data model.
  • Because stock tickers (exchange symbols like NVO) change when companies rebrand and get reassigned to unrelated companies years later, restrictions never point to ticker strings. Every rule points to a permanent internal surrogate key (sec_id, an arbitrary integer assigned once per instrument and never reused), while a bitemporal identifier_map records which ticker+exchange (MIC, Market Identifier Code) mapped to which sec_id over which dates.

A naive schema breaks both live trading and regulatory audits. Keying restrictions by ticker means a 2023 restriction on Issuer Alpha (NVO) will falsely block an innocent 2024 IPO that reuses symbol NVO, while letting Issuer Alpha slip past the ban after renaming its symbol to NVX! Storing only effective_date and end_date (one timeline) or UPDATE-ing rows in place makes every retroactive rule or typo fix look as though past trades were approved illegally, destroying audit evidence. Finally, caching "is NVO restricted today? -> True/False" in Redis with a 60-second TTL silently serves wrong answers across midnight rollovers and retroactive edits.

Mini concrete walkthrough

Let's trace four real events through the schema:

  1. Ticker rename & reuse: Issuer Alpha (sec_id = 501) trades on NYSE (XNYS) as NVO during [2016-05-02, 2023-09-01), then renames to NVX [2023-09-01, infinity). In 2024, unrelated Issuer Beta (sec_id = 804) takes NVO [2024-03-01, infinity). When someone asks "Was symbol NVO on XNYS restricted on 2023-04-10?", identifier_map resolves ('TICKER', 'NVO', 'XNYS', 2023-04-10) to sec_id = 501 (Issuer Alpha), completely unaffected by Issuer Beta owning NVO today!
  2. Overlapping rules with priorities: On 2023-04-14, sec_id = 501 matches Japanese regulator rule R14 (BLOCK, priority 100, country = 'JP'), internal policy R21 (WARN, priority 50, global), and desk exemption R29 (ALLOW, priority 60, entity = 'DESK4'). An order from DESK4 in the US matches [R21, R29] -> highest priority 60 wins -> ALLOW. An order from DESK7 in Japan matches [R14, R21] -> highest priority 100 wins -> BLOCK.
  3. Retroactive correction without losing history: Suppose R14 was mistakenly entered with end_date = 2023-06-30 (valid_to = 2023-07-01) and fixed on 2023-07-05 14:00Z to 2023-05-31 (valid_to = 2023-06-01). Version 1 closes (sys_to = 2023-07-05 14:00Z) and Version 2 opens (sys_from = 2023-07-05 14:00Z, sys_to = 'infinity'). Auditing 2023-06-15 as of June 20 returns Version 1 (BLOCK, explaining why June's trade was rejected), while querying as of today returns Version 2 (ALLOW).
  4. Microsecond order-entry check: Each Check Service instance holds the ~50 MB sys_to = 'infinity' slice in RAM, tailing monotonic changes(change_id) every 100 ms, and returns {decision: "BLOCK", knowledge_version: 884214} in < 1 ms.

Key trade-offs

  • Bitemporal tables vs. current-state table + audit log: Storing both [valid_from, valid_to) and [sys_from, sys_to) adds four columns per table and requires close-then-insert transactions, but turns any historical "as known at timestamp T" audit into one declarative SQL filter—whereas reconstructing past state by replaying an audit log is slow and fragile.
  • Surrogate sec_id + identifier_map vs. ticker or ISIN primary keys: Isolating rules on an immutable sec_id makes ticker renames and symbol reuse harmless (and handles rare ISIN changes after corporate redomiciliations), trading off a mandatory date-aware identifier resolution step and explicit 409 AMBIGUOUS_IDENTIFIER responses when callers omit an exchange MIC.
  • Unbounded ['-infinity', 'infinity') on fixed rule targets vs. dated join rows on dynamic lists: Putting bitemporal columns on restriction_targets supports both static single-security rules (using unbounded target membership so extending a rule's end_date in restriction_versions updates 1 row instead of clipping on stale target dates) and dynamic sanctions lists where individual securities join or leave over time, at the cost of checking date predicates on both restriction_versions and restriction_targets.
  • Half-open [valid_from, valid_to) storage vs. inclusive end_date columns: Storing exclusive valid_to = end_date + 1 day prevents +1/-1 boundary bugs and unlocks PostgreSQL GiST exclusion constraints (which reject overlapping active ranges at commit time), requiring a trivial +1 / -1 day translation at the API layer.
  • Priority first, then BLOCK > WARN > ALLOW tie-breaking: Checking priority first lets authorized compliance exemptions (ALLOW at priority 60) override lower-priority internal policies (priority 50) while authorities.max_priority caps internal teams below regulators (priority 100); breaking equal-priority ties by strictest effect fails safe on conflicting rules.
  • Single serialized writer (change_counter) + in-RAM row cache vs. concurrent writers + Redis boolean cache: Serializing ~500 writes/day (~1/min) adds zero noticeable write latency while producing gap-free monotonic change_ids that ~50 MB in-memory check instances tail every 100 ms—delivering microsecond checks that never go stale at midnight or on retroactive rules, unlike TTL key-value caches.

Common mistakes

  • Using ticker (or even ISIN) as the foreign key on restrictions: Reused tickers block innocent companies, renamed tickers let restricted companies trade unchecked, and corporate restructurings can even change ISINs.
  • Resolving a ticker as of today when entering a retroactive rule: Entering a retroactive 2023 ban on "NVO" in 2025 and resolving "NVO" against today's security master attaches the ban to whichever company owns "NVO" in 2025 instead of the 2023 company!
  • Tracking only valid time (effective_date, end_date) or updating rows in place: Without [sys_from, sys_to), fixing a typo or adding a retroactive restriction rewrites history and makes previously lawful trades look like compliance violations during regulatory audits.
  • Omitting CHECK (valid_from < valid_to) or plugging :t = 'infinity' into :t < sys_to: Zero-length ranges evaluate to 'empty' in PostgreSQL daterange (silently bypassing GiST && overlap constraints!), and 'infinity' < 'infinity' evaluates to FALSE (use sys_to = 'infinity' for current-knowledge queries so partial indexes apply).
  • Ordering history with PostgreSQL now() across concurrent transactions: now() records when a transaction started, not when it committed, which can invert visibility order on historical as_of replays unless serialized with a monotonic change_id.
  • Caching boolean "is restricted" results with a TTL or failing open on timeouts: A 60-second TTL misses newly enacted bans, breaks at midnight date rollovers, and misses retroactive rules; compliance checks at order entry must fail closed (hold orders) when freshness cannot be verified.
  • Auto-rewriting restrictions on mergers or spin-offs: Whether an internal watch-list or regulatory ban transfers to an acquiring company is a legal decision requiring human compliance sign-off, not an automated SQL trigger.

Follow-up questions

  • Suppose compliance discovers today that a restriction active last month had the wrong date window—how do you record the correction while preserving last month's audit trail? Never overwrite last month's row. Execute an atomic bitemporal update with change_kind = 'CORRECTION' (or 'CANCEL' with is_active = FALSE if the rule never should have existed): lock change_counter, close the erroneous version's sys_to = :now, insert version v + 1 with the corrected [valid_from, valid_to) and sys_from = :now, sys_to = 'infinity', and emit the new change_id. Because Version 1 remains intact for sys_time < :now, auditors can still reproduce why orders last month were blocked or allowed under what the system knew then. Immediately afterward, run an automated retroactive impact report over the Order Decision Log for the affected securities and valid dates: recompute each historical order under today's knowledge_version and diff it against the decision originally recorded on the order—flagging any trade that was ALLOWed last month but should have been BLOCKed as a compliance exception for legal review and regulatory self-reporting.
  • How would you keep the versioned instrument master and the restriction evaluation engine consistent during a bulk vendor refresh or a full identifier migration? Keep both identifier_map / securities and restrictions in the same PostgreSQL database sharing the single changes(change_id) log, enforce foreign keys to immutable sec_ids (never deleting sec_ids), and load bulk vendor files into a staging table first. Staging runs automated pre-flight checks—PostgreSQL GiST non-overlap constraints, row-count churn limits, and verifying every active restriction_targets.sec_id retains valid identifier metadata—before committing the entire batch in one transaction under a single change_id so in-memory Check Service instances swap the entire batch atomically without ever exposing a half-updated state. For a full system migration to a new security-master provider or new sec_id numbering scheme, build a deterministic old_sec_id <-> new_sec_id crosswalk table, replay all historical order checks offline plus shadow-check 100% of live OMS traffic across both engines until discrepancies hit zero, and briefly pause rule writes during final cutover.
  • How would you structure caching so pre-trade order checks run at sub-millisecond latency without ever serving stale compliance decisions? Cache the active bitemporal data rows (~50 MB total) inside each Check Service process's RAM—never precomputed boolean answers per (sec_id, date)! At startup, an instance opens one REPEATABLE READ snapshot to read K = last_change_id along with all sys_to = 'infinity' rows from restriction_versions, restriction_targets, and identifier_map, indexing them in memory by sec_id and (id_type, id_value, mic); it then polls changes WHERE change_id > K every 100 ms to apply updates in strict order. Because the in-memory structs preserve [valid_from, valid_to) ranges, retroactive edits, future-dated rules, and midnight date rollovers work with zero cache-invalidation races while answering checks in microseconds and returning knowledge_version = K on every decision. Accuracy during network hiccups is guaranteed by a 2-second freshness guard (any instance unable to confirm its K matches the primary's latest change_id within 2 seconds stops serving traffic, and urgent rules wait ~100–200 ms for all active instances to acknowledge K >= new_change_id before reporting "Enforced").

Follow-up questions

Similar questions

More Jain Global interview questions

All 5 Jain Global questions →