Design a Bitemporal Compliance Engine for Securities Trading
System DesignModel answerLast updated
Design a bitemporal data model and low-latency system architecture to track effective-dated trading compliance rules and dynamic security identifier resolutions.
In modern financial markets, regulatory bodies and internal risk control teams regularly institute trading restrictions (such as full trading bans, pre-approval requirements, or short-sale blocks). Enforcing these restrictions is complicated by two facts:
- Business rules have complex valid dates (including retroactive applications and future-dated policies).
- Securities regularly undergo identifier changes (such as symbol/ticker changes, venue transfers, ISIN updates, or corporate restructuring), meaning human-readable tickers cannot serve as static keys.
Design a scalable system architecture and bitemporal data layer to store, manage, and query trading compliance restrictions.
System Requirements
- Bitemporal Data Architecture: The data model must track both Valid Time (when a restriction or identifier mapping is active in the business world) and System Time (when the database recorded that knowledge). The system must support retroactive entries while maintaining complete, point-in-time auditability.
- Identifier Resolution: Resolve market identifiers (e.g., Ticker
XYZon exchangeXNYS) to the underlying permanent entity as of any historical date. Explain how your schema handles ticker reuse across different time windows and execution venues without introducing look-ahead bias. - Multi-Layered Rule Resolution: Multiple active restrictions might apply simultaneously to the same asset (e.g., an internal policy, a country-level regulatory ban, and an account-level lock). Define deterministic precedence and conflict-resolution rules across overlapping policies.
- Pre-Trade High Throughput & Auditability: The engine must serve real-time pre-trade validation checks during market peak hours while guaranteeing point-in-time snapshot checks ($as_of$) for regulatory audits.
Scope & Constraints
- Security Universe: ~100,000 active securities; historical mapping table will contain several million rows.
- Write Volume: ~500 rule adjustments/ingestions per day by compliance officers.
- Read Latency & Throughput: Peak load of 25,000 pre-trade check requests/sec with a $p99 \le 5\text{ ms}$.
- Safety: Fail-closed semantics for invalid, ambiguous, or unresolvable identifiers.
Hints
Hint 1
Model two distinct time dimensions on every record: Valid Time (valid_from, valid_to) for real-world application and System Time (sys_from, sys_to) for database record ingestion history.
Hint 2
Never attach compliance rules directly to temporary identifiers like tickers; map tickers to an immutable internal surrogate key (sec_id) valid for a specific date range.
Hint 3
To maintain p99 < 5ms under heavy read traffic, separate the relational database of record from an in-memory evaluation cache refreshed via an event-driven change-data-capture stream.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. System Requirements & Scale Context
Key Metrics & Load Profile
- Asset Universe: 100,000 active securities. Including historical lineage and ticker changes over a 10-year window, identifier mappings scale to ~1–2 million rows.
- Write Volume: ~500 updates/day. Write volume is low, but correctness and transaction integrity are critical.
- Read Throughput: Up to 25,000 requests/sec during market opening bell peaks.
- Latency Target: $p99 < 5\text{ ms}$ for real-time order checks in the critical path.
- Auditability: Complete snapshot capability to reconstruct system state for any arbitrary pair of $(\text{valid_date}, \text{system_timestamp})$.
Key Design Principles
- Bitemporal Dual-Axis Tracking:
- Valid Time ($V$): Date range
[valid_from, valid_to]indicating when a rule applies in the real world. - System Time ($S$): Timestamp range
[sys_from, sys_to)indicating when this knowledge was present in the system memory.
- Valid Time ($V$): Date range
- Entity-Centric Mapping: Compliance constraints attach to immutable internal keys (
sec_idorissuer_id), never to mutable market identifiers (tickers, CUSIPs). - Fail-Closed Default: If an identifier cannot be deterministically resolved to a single active entity for the given trade date, the system defaults to blocking the order and raising an audit flag.
2. Bitemporal Database Schema Design
The target storage engine must support range types and exclusion constraints (e.g., PostgreSQL). All core tables adopt bitemporal range tracking.
-- Core static entity representing an issuing organization
CREATE TABLE issuer (
issuer_id BIGINT PRIMARY KEY,
legal_name TEXT NOT NULL,
country_of_risk VARCHAR(2) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Core static asset entity (never reassigned, never changes meaning)
CREATE TABLE security (
sec_id BIGINT PRIMARY KEY,
issuer_id BIGINT NOT NULL REFERENCES issuer(issuer_id),
asset_class VARCHAR(32) NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Bitemporal identifier mapping table (Ticker, ISIN, CUSIP -> sec_id)
CREATE TABLE identifier_map (
mapping_id BIGINT GENERATED ALWAYS AS IDENTITY,
sec_id BIGINT NOT NULL REFERENCES security(sec_id),
id_type VARCHAR(16) NOT NULL, -- 'TICKER', 'ISIN', 'SEDOL'
id_value VARCHAR(32) NOT NULL,
mic VARCHAR(8) NOT NULL, -- Market Identifier Code (e.g., 'XNYS', 'XNAS')
-- Valid time (inclusive date range)
valid_from DATE NOT NULL,
valid_to DATE NOT NULL DEFAULT '9999-12-31',
-- System time (half-open timestamp range)
sys_from TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
sys_to TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
PRIMARY KEY (mapping_id),
-- Exclusion constraint prevents overlapping active mappings for identical venue/ticker pairs
EXCLUDE USING gist (
id_type WITH =,
id_value WITH =,
mic WITH =,
daterange(valid_from, valid_to, '[]') WITH &&,
tstzrange(sys_from, sys_to, '[)') WITH &&
)
);
-- Bitemporal compliance rule repository
CREATE TABLE restriction_rule (
rule_id BIGINT NOT NULL,
version INT NOT NULL DEFAULT 1,
authority VARCHAR(64) NOT NULL, -- e.g., 'SEC', 'INTERNAL_RISK', 'EU_ESMA'
priority INT NOT NULL, -- Higher values indicate higher priority
action VARCHAR(16) NOT NULL, -- 'BLOCK', 'PRE_CLEAR', 'WARN', 'ALLOW'
jurisdiction VARCHAR(8) NOT NULL, -- 'US', 'EU', 'GLOBAL'
-- Scope granularity (NULL values act as wildcards)
entity_id BIGINT,
account_id BIGINT,
side VARCHAR(4), -- 'BUY', 'SELL', NULL (both)
-- Valid & System time dimensions
valid_from DATE NOT NULL,
valid_to DATE NOT NULL DEFAULT '9999-12-31',
sys_from TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
sys_to TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
reason TEXT NOT NULL,
created_by VARCHAR(64) NOT NULL,
PRIMARY KEY (rule_id, version)
);
-- Mapping target entities to specific restriction rules
CREATE TABLE restriction_target (
rule_id BIGINT NOT NULL,
rule_version INT NOT NULL,
target_type VARCHAR(16) NOT NULL, -- 'SECURITY', 'ISSUER'
target_id BIGINT NOT NULL, -- Points to sec_id or issuer_id
valid_from DATE NOT NULL,
valid_to DATE NOT NULL DEFAULT '9999-12-31',
sys_from TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
sys_to TIMESTAMPTZ NOT NULL DEFAULT 'infinity',
PRIMARY KEY (rule_id, rule_version, target_type, target_id),
FOREIGN KEY (rule_id, rule_version) REFERENCES restriction_rule(rule_id, version)
);
CREATE INDEX idx_id_map_lookup
ON identifier_map (id_type, id_value, mic, valid_from, valid_to)
WHERE sys_to = 'infinity';
CREATE INDEX idx_target_sec
ON restriction_target (target_id, target_type, valid_from, valid_to)
WHERE sys_to = 'infinity';
3. Historic Identifier Resolution & Audit Query
Ticker Resolution Mechanics
When a trade order arrives with Ticker XYZ for execution on 2023-04-15, the engine must resolve XYZ based on what the system knew as of the execution timestamp (or current system time if live).
-- Dynamic resolution of Ticker to primary Security ID and linked Rules
WITH target_asset AS (
SELECT
m.sec_id,
s.issuer_id
FROM identifier_map m
JOIN security s ON s.sec_id = m.sec_id
WHERE m.id_type = 'TICKER'
AND m.id_value = :ticker_symbol
AND m.mic = :exchange_mic
-- Valid Time Check
AND :trade_date BETWEEN m.valid_from AND m.valid_to
-- System Time Check (Point-in-Time Audit Support)
AND :as_of_timestamp >= m.sys_from
AND :as_of_timestamp < m.sys_to
LIMIT 1
)
SELECT
r.rule_id,
r.version,
r.authority,
r.priority,
r.action,
r.reason
FROM target_asset ta
JOIN restriction_target rt
ON (rt.target_type = 'SECURITY' AND rt.target_id = ta.sec_id)
OR (rt.target_type = 'ISSUER' AND rt.target_id = ta.issuer_id)
JOIN restriction_rule r
ON r.rule_id = rt.rule_id
AND r.version = rt.rule_version
WHERE :trade_date BETWEEN r.valid_from AND r.valid_to
AND :trade_date BETWEEN rt.valid_from AND rt.valid_to
AND :as_of_timestamp >= r.sys_from AND :as_of_timestamp < r.sys_to
AND :as_of_timestamp >= rt.sys_from AND :as_of_timestamp < rt.sys_to
AND (r.jurisdiction = :trade_jurisdiction OR r.jurisdiction = 'GLOBAL')
AND (r.side IS NULL OR r.side = :order_side)
AND (r.account_id IS NULL OR r.account_id = :trade_account_id)
ORDER BY r.priority DESC;
4. Rule Precedence and Evaluation Logic
If a search returns multiple active rules, the decision engine evaluates them using a multi-step precedence algorithm:
+-----------------------------+
| Retrieve Matching Rules |
+--------------+--------------+
|
v
+-----------------------------+
| Sort Rules by Priority DESC |
+--------------+--------------+
|
v
+-----------------------------+
| Any Top Priority Rules Have |
| Explicit 'ALLOW'? |
+-------+-------------+-------+
| |
Yes | | No
+-----------------+ +-----------------+
| |
v v
+-----------------------+ +-----------------------+
| Return ALLOW Decision | | Pick Highest Severity |
| (Overrides lower-prio | | Action: |
| BLOCK rules) | | BLOCK > PRE_CLEAR > |
+-----------------------+ | WARN > ALLOW |
+-----------------------+
- Priority Score Ordering: Rules with higher numerical
priorityscores dominate lower priority rules. - Explicit
ALLOWExemption Overrides: An explicitALLOWaction overrides restrictive actions (BLOCK,WARN) only if its priority score is greater than or equal to the restrictive rule's priority score. - Severity Resolution for Equal Priority: If rules have identical priority levels, the engine selects the most restrictive policy according to this hierarchy: $$\text{BLOCK} > \text{PRE_CLEAR} > \text{WARN} > \text{ALLOW}$$
5. End-to-End System Architecture
Executing complex SQL queries against a bitemporal relational database during the hot path of order routing will violate the sub-5ms $p99$ requirement. The production architecture uses CQRS (Command Query Responsibility Segregation) to decouple system updates from low-latency reads.
+------------------------+
| Compliance Admin Console|
+-----------+------------+
| Write / Edit Rule
v
+------------------------+ CDC +-------------------------+
| PostgreSQL (Bitemporal | -------------> | Kafka Event Stream |
| System of Record) | (Debezium) +------------+------------+
+------------------------+ |
v
+-------------------------+
| In-Memory Evaluation |
| Engine Cluster (Redis / |
| Local Cache Nodes) |
+------------+------------+
^
| Evaluation Request
| (< 5ms p99)
+------------+------------+
| Pre-Trade Order Gateway |
+-------------------------+
Architectural Components
- Bitemporal RDBMS (System of Record): PostgreSQL stores the source of truth, enforcing temporal constraints, uniqueness, and immutability via system triggers and transaction controls.
- Change Data Capture (CDC) Pipeline: Debezium monitors PostgreSQL WAL logs and streams row modifications to Kafka topics.
- In-Memory Rule Evaluator (Read Path):
- Maintained in memory (e.g., Redis cluster or local C++ / Rust process cache inside the trading gateway).
- Keeps current valid-time state (
sys_to = 'infinity') indexed bysec_idand active(id_type, id_value, mic)tuples. - Evaluates incoming order payloads against pre-compiled decision trees in under $1\text{ ms}$.
- Historical Audit Service: Queries the underlying bitemporal PostgreSQL store for point-in-time snapshot replays ($as_of < \text{now}$) for compliance reporting and regulatory audits.
6. Edge Cases & Operational Pitfalls
- Retroactive Adjustments (Backdating): When a compliance officer adds a rule effective two weeks ago, the database updates the historic
sys_toof affected current records toNOW(), inserts the backdated row withsys_from = NOW(), and emits a backfill CDC event. The engine triggers an automated post-trade audit replay to flag trades that executed during that window. - Ticker Reuse Across Venues & Time: Tickers are not globally unique. Ticker
APPmight represent different companies on the London Stock Exchange (XLON) vs. NASDAQ (XNAS). The schema enforces compound isolation using(id_type, id_value, mic, valid_range, sys_range). - Fail-Closed on Unknown Identifier: If a trade arrives for an unrecognized ticker or during an unmapped validity gap, the evaluation engine returns
DECISION: BLOCKwith reasonUNRESOLVED_IDENTIFIER_SAFETY_SHUTDOWN.