Databricks LTAP, Lakebase, and Real-Time Analytics for Institutional Market Liquidity Depth
Speaker background
The speaker moved from military combat engineering into institutional-grade trading and now provides market-liquidity depth analysis to international trading desks.
Combat engineering and institutional liquidity analysis share an operational discipline. A combat engineer evaluates terrain, load capacity, routes, obstacles, redundancy, failure points, and the time required to restore a passage. A liquidity analyst evaluates order-book depth, executable capacity, market impact, venue resilience, stale prices, fragmented routes, and the time required to enter or exit a position.
The core question is similar: can the route support the intended load under current conditions, and what happens if a critical component fails?
This guide builds a Databricks Free Edition prototype that combines transactional data capture, streaming market events, lakehouse analytics, and low-latency serving. It explains the relationship between online transaction processing, online analytical processing, Databricks Lake Transactional/Analytical Processing, Lakebase Postgres, Structured Streaming real-time mode, Lakehouse Real-Time, and Unity Catalog.
Scope of the prototype
The prototype records institutional market-liquidity observations and analyst decisions while continuously calculating market-depth indicators.
The workflow supports the following research activities:
- Record analyst watchlists, thresholds, notes, and investigation status as transactional data.
- Ingest synthetic or properly licensed market-depth events.
- Calculate spread, depth, imbalance, slippage, market impact, and liquidity-resilience indicators.
- Maintain current liquidity state and historical observations.
- Query governed Delta tables through Databricks SQL.
- Serve selected analytical results to a low-latency application database when Lakebase is available.
- Explain how production Lakehouse Real-Time can support sub-second analytical reads at high concurrency.
The prototype does not place orders, route trades, transfer funds, or connect to a production execution-management system. Free Edition is not a production trading platform.
Databricks Free Edition boundary
Databricks Free Edition is a perpetual, no-cost, serverless-only environment for learning and experimentation. The environment is quota-limited and does not include guaranteed reliability, support, or a service-level agreement.
Free Edition provides serverless notebook compute, one limited SQL warehouse, default storage, Unity Catalog capabilities, Databricks Apps, Lakeflow features, Genie, and access to Lakebase where enabled. Feature availability can vary by region, cloud, preview status, and workspace configuration.
Use Free Edition to prove the data model, streaming calculations, SQL logic, application workflow, and governance concepts. Move to a paid Databricks account before using confidential trading data, licensed real-time exchange feeds, material positions, counterparty information, client data, or operational decision workflows.
OLTP, OLAP, and LTAP
Online transaction processing, or OLTP, is optimized for frequent, small, concurrent changes. Examples include creating a watchlist, updating a liquidity threshold, acknowledging an alert, writing an analyst note, or changing the status of an investigation. An OLTP system normally requires low-latency inserts and updates, transaction isolation, indexes, primary keys, and predictable point lookups.
Online analytical processing, or OLAP, is optimized for scanning, filtering, joining, and aggregating large datasets. Examples include measuring average spread across a month, estimating slippage by order size, comparing venue resilience, calculating liquidity around an announcement, and identifying repeated periods of shallow depth.
Traditional architectures normally place OLTP data in PostgreSQL, MySQL, SQL Server, or Oracle and move copies into a warehouse or lakehouse using change data capture. That creates a synchronization pipeline, duplicated data, delay, operational cost, and governance complexity.
Databricks Lake Transactional/Analytical Processing, or LTAP, is an architecture that serves transactional and analytical workloads from a unified storage layer in the lake under one governance model. LTAP is not one product switch. It is implemented through Lakebase capabilities that separate PostgreSQL compute from durable cloud storage and make operational records available to lakehouse engines without maintaining the traditional second analytical copy.
Lakebase remains appropriate for row-oriented transactional access. Delta and Iceberg tables remain appropriate for large analytical scans. LTAP unifies the storage and governance layer while allowing each workload to use a suitable execution engine.
Lakebase role
Lakebase is a fully managed PostgreSQL service integrated with Databricks. It supports standard PostgreSQL clients and workflows, automatic scaling, scale to zero, instant branching, read replicas, point-in-time restore, high availability options, regional disaster recovery capabilities, Unity Catalog integration, and synchronization between PostgreSQL and lakehouse data.
For this use case, Lakebase stores operational application state such as watchlists, alert acknowledgements, analyst cases, threshold changes, and workflow status. The lakehouse stores large volumes of market events and derived historical metrics.
Lakebase can also serve selected Unity Catalog tables to an application for low-latency reads. PostgreSQL changes can be stored as Delta data for analytics and audit when the relevant capability is available.
A Free Edition Lakebase project should be treated as a learning resource. Scale-to-zero behavior, quotas, regional availability, and feature limits must be checked in the workspace.
Structured Streaming real-time mode
Structured Streaming traditionally processes events using micro-batches. A micro-batch collects records for a short interval and then processes them together. This model provides strong throughput and fault tolerance but adds scheduling and batch-boundary latency.
Databricks real-time mode refactors the execution path for lower latency and processes data continuously rather than waiting for normal micro-batch boundaries. Direct Structured Streaming real-time mode has compute and runtime requirements. Serverless real-time processing is provided through supported Lakeflow pipeline configurations, while direct API execution can require classic compute and an appropriate Databricks Runtime.
Because Free Edition is serverless-only, do not assume that every direct classic-compute real-time-mode example can run there. Build the Free Edition version with serverless-supported streaming or trigger modes, and treat specialized real-time mode as a production extension where the required Lakeflow or compute capability is enabled.
Lakehouse Real-Time role
Lakehouse Real-Time, also written Lakehouse//RT, is a serverless analytical warehouse designed for low-latency, high-concurrency reads against Unity Catalog tables stored in Delta Lake or Apache Iceberg formats.
The Beta documentation describes sub-second SQL read latency for hundreds to thousands of concurrent users. It is intended for operational analytics, custom applications, and BI dashboards. It requires a supported region and preview enablement and is not guaranteed to be available in Free Edition.
Do not confuse the two real-time capabilities:
- Structured Streaming real-time mode reduces event-processing latency.
- Lakehouse//RT reduces analytical query-serving latency and increases query concurrency.
A production architecture can use both. Streaming updates the current analytical state, and Lakehouse//RT serves that state to many users.
Step 1: Create and inspect the Free Edition workspace
Open the Databricks Free Edition sign-up page and create a workspace.
Use a project name that makes the non-production status explicit:
institutional_liquidity_ltap_free_nonprod
Open the workspace and confirm access to Workspace, Catalog, SQL Editor, SQL Warehouses, Jobs and Pipelines, and Lakebase where available.
Create a project directory:
/Workspace/Users/<your-user>/institutional_liquidity_ltap
Create these folders:
00_environment01_reference_data02_market_ingestion03_streaming_metrics04_lakebase05_sql_analytics06_application07_governance
Create a notebook named 00_environment_check.
Run:
SELECT current_user() AS current_user, current_catalog() AS current_catalog, current_schema() AS current_schema, current_timestamp() AS checked_at; Record the Free Edition constraints in a README:
- The workspace is for learning and prototyping.
- Compute is serverless-only.
- Usage is subject to fair-use quotas.
- The SQL warehouse is limited.
- Applications and Lakebase resources can scale to zero.
- Preview capabilities might be unavailable.
- No production reliability or latency commitment applies.
Step 2: Define the institutional liquidity-depth model
Use a normalized event model. One market-depth event represents the observable state of one venue, instrument, and price level at one event time.
Required identifiers:
event_idevent_timereceived_timevenueinstrumentasset_classcurrencysidepricequantitylevel_numberevent_typesequence_numbersource_systemis_synthetic
Use event types such as SNAPSHOT, ADD, MODIFY, DELETE, and TRADE.
Store event time and receive time separately. Their difference is feed latency:
feed_latency_ms = received_time - event_time
Define top-of-book spread:
spread = best_ask - best_bid
Define spread in basis points:
spread_bps = (best_ask - best_bid) / midpoint * 10000
Define depth within a price-distance band:
bid_depth_10bps = sum(bid quantity where bid price >= midpoint * (1 - 0.001))
ask_depth_10bps = sum(ask quantity where ask price <= midpoint * (1 + 0.001))
Define order-book imbalance:
imbalance = (bid_depth - ask_depth) / (bid_depth + ask_depth)
The value normally ranges from negative one to positive one. A positive value indicates more modeled bid depth than ask depth in the selected band. It does not guarantee that price will rise.
Define estimated buy slippage for a target order size as the volume-weighted average execution price across ask levels minus the best ask. Define sell slippage using bid levels.
Define resilience after a shock:
resilience_seconds = first time depth returns to 80 percent of pre-shock depth - shock time
Treat 80 percent as a configurable research threshold rather than a universal market standard.
Define stale depth using both event age and sequence behavior. For a prototype, mark an instrument stale if no new event arrives for five seconds. For a real institutional feed, choose the threshold by venue, asset class, session, and contractual feed behavior.
Step 3: Create Unity Catalog objects
Open SQL Editor and select the Free Edition SQL warehouse.
Create a catalog and schemas. If the workspace does not permit catalog creation, use the default catalog and create the schemas there.
CREATE CATALOG IF NOT EXISTS market_liquidity; CREATE SCHEMA IF NOT EXISTS market_liquidity.raw; CREATE SCHEMA IF NOT EXISTS market_liquidity.silver; CREATE SCHEMA IF NOT EXISTS market_liquidity.gold; CREATE SCHEMA IF NOT EXISTS market_liquidity.reference; CREATE SCHEMA IF NOT EXISTS market_liquidity.governance; Create the raw event table:
CREATE TABLE IF NOT EXISTS market_liquidity.raw.depth_events ( event_id STRING, event_time TIMESTAMP, received_time TIMESTAMP, venue STRING, instrument STRING, asset_class STRING, currency STRING, side STRING, price DECIMAL(24,10), quantity DECIMAL(24,8), level_number INT, event_type STRING, sequence_number BIGINT, source_system STRING, is_synthetic BOOLEAN, ingestion_time TIMESTAMP ) USING DELTA; Create a venue reference table:
CREATE TABLE IF NOT EXISTS market_liquidity.reference.venues ( venue STRING, jurisdiction STRING, timezone STRING, asset_class STRING, market_open_local STRING, market_close_local STRING, expected_feed_interval_ms BIGINT, source_license STRING, active BOOLEAN, reviewed_at TIMESTAMP ) USING DELTA; Create an instrument reference table:
CREATE TABLE IF NOT EXISTS market_liquidity.reference.instruments ( instrument STRING, asset_class STRING, base_asset STRING, quote_asset STRING, tick_size DECIMAL(24,10), lot_size DECIMAL(24,8), contract_multiplier DECIMAL(24,8), price_scale INT, quantity_scale INT, active BOOLEAN ) USING DELTA; Create a quality issue table:
CREATE TABLE IF NOT EXISTS market_liquidity.governance.quality_issues ( issue_id STRING, event_id STRING, detected_at TIMESTAMP, issue_type STRING, issue_detail STRING, severity STRING, resolution_status STRING ) USING DELTA; Step 4: Generate or upload safe market-depth data
Use synthetic data for the first prototype. Do not upload licensed exchange data to Free Edition unless the license and security policy explicitly allow it.
Create a CSV or JSON dataset with at least two venues, three instruments, both order-book sides, ten price levels, and several thousand timestamped updates.
For demonstration purposes, use synthetic instruments such as:
FX_USD_SGD_SIMFX_USD_KRW_SIMFUT_EQ_INDEX_SIM
Mark every event with is_synthetic = true.
Upload the file through Catalog Explorer or the notebook file interface.
Load the file into the raw Delta table. Adjust the uploaded path to the path shown by the workspace.
COPY INTO market_liquidity.raw.depth_events FROM '/Volumes/market_liquidity/raw/uploads/depth_events' FILEFORMAT = JSON FORMAT_OPTIONS ('inferSchema' = 'true') COPY_OPTIONS ('mergeSchema' = 'true'); If COPY INTO is not appropriate for the uploaded location, use a serverless notebook:
from pyspark.sql import functions as F source_path = "/Volumes/market_liquidity/raw/uploads/depth_events" raw_df = ( spark.read .format("json") .load(source_path) .withColumn("ingestion_time", F.current_timestamp()) ) (raw_df.write .format("delta") .mode("append") .saveAsTable("market_liquidity.raw.depth_events")) Confirm the load:
SELECT venue, instrument, COUNT(*) AS event_count, MIN(event_time) AS first_event, MAX(event_time) AS last_event FROM market_liquidity.raw.depth_events GROUP BY venue, instrument ORDER BY venue, instrument; Step 5: Apply market-feed quality controls
Create a validated view:
CREATE OR REPLACE VIEW market_liquidity.silver.depth_events_validated AS SELECT *, timestampdiff(MILLISECOND, event_time, received_time) AS feed_latency_ms, CASE WHEN event_id IS NULL THEN 'MISSING_EVENT_ID' WHEN event_time IS NULL THEN 'MISSING_EVENT_TIME' WHEN received_time < event_time THEN 'NEGATIVE_FEED_LATENCY' WHEN side NOT IN ('BID', 'ASK') THEN 'INVALID_SIDE' WHEN price <= 0 THEN 'INVALID_PRICE' WHEN quantity < 0 THEN 'INVALID_QUANTITY' WHEN level_number < 1 THEN 'INVALID_LEVEL' ELSE 'VALID' END AS quality_status FROM market_liquidity.raw.depth_events; Check duplicate events:
SELECT event_id, COUNT(*) AS duplicate_count FROM market_liquidity.raw.depth_events GROUP BY event_id HAVING COUNT(*) > 1; Check sequence gaps:
WITH sequenced AS ( SELECT venue, instrument, sequence_number, LAG(sequence_number) OVER ( PARTITION BY venue, instrument ORDER BY sequence_number ) AS previous_sequence_number FROM market_liquidity.raw.depth_events ) SELECT * FROM sequenced WHERE previous_sequence_number IS NOT NULL AND sequence_number <> previous_sequence_number + 1; A sequence gap can invalidate the reconstructed book. Do not fill it by assuming no change. Mark the instrument as requiring a fresh snapshot.
Check crossed or locked books after reconstruction. A crossed book has best bid greater than best ask. A locked book has equal best bid and best ask. These states can represent valid market conditions, feed timing, or reconstruction errors depending on the source. Preserve the evidence and apply source-specific rules.
Step 6: Create a Structured Streaming pipeline
Create a notebook named 03_streaming_liquidity_metrics.
Read new Delta events as a stream:
from pyspark.sql import functions as F source = ( spark.readStream .table("market_liquidity.raw.depth_events") .filter("price > 0 AND quantity >= 0") .withWatermark("event_time", "30 seconds") ) Create a time-windowed liquidity aggregate:
windowed_depth = ( source .groupBy( F.window("event_time", "5 seconds", "1 second"), "venue", "instrument", "side" ) .agg( F.sum("quantity").alias("observed_quantity"), F.count("event_id").alias("event_count"), F.max("received_time").alias("latest_received_time"), F.max("sequence_number").alias("latest_sequence_number") ) .select( F.col("window.start").alias("window_start"), F.col("window.end").alias("window_end"), "venue", "instrument", "side", "observed_quantity", "event_count", "latest_received_time", "latest_sequence_number" ) ) Write the streaming result:
query = ( windowed_depth.writeStream .format("delta") .outputMode("append") .option( "checkpointLocation", "/Volumes/market_liquidity/raw/checkpoints/windowed_depth" ) .trigger(processingTime="5 seconds") .toTable("market_liquidity.silver.windowed_depth") ) This Free Edition baseline uses a processing-time trigger. It remains a micro-batch implementation. It is appropriate for validating schemas, watermarks, checkpoints, and metrics, but it does not prove millisecond-level processing.
Keep the checkpoint path stable. Deleting a checkpoint can cause reprocessing or altered state behavior. Create a new checkpoint for material query changes.
Step 7: Calculate current depth and liquidity indicators
Create a top-of-book view from the latest valid observations:
CREATE OR REPLACE VIEW market_liquidity.gold.top_of_book AS WITH ranked AS ( SELECT venue, instrument, side, price, quantity, event_time, ROW_NUMBER() OVER ( PARTITION BY venue, instrument, side ORDER BY event_time DESC, sequence_number DESC, level_number ASC ) AS row_number FROM market_liquidity.silver.depth_events_validated WHERE quality_status = 'VALID' ) SELECT venue, instrument, MAX(CASE WHEN side = 'BID' AND row_number = 1 THEN price END) AS best_bid, MAX(CASE WHEN side = 'ASK' AND row_number = 1 THEN price END) AS best_ask, MAX(CASE WHEN side = 'BID' AND row_number = 1 THEN quantity END) AS best_bid_quantity, MAX(CASE WHEN side = 'ASK' AND row_number = 1 THEN quantity END) AS best_ask_quantity, MAX(event_time) AS latest_event_time FROM ranked WHERE row_number = 1 GROUP BY venue, instrument; Create spread metrics:
CREATE OR REPLACE VIEW market_liquidity.gold.spread_metrics AS SELECT *, (best_bid + best_ask) / 2 AS midpoint, best_ask - best_bid AS spread, (best_ask - best_bid) / NULLIF((best_bid + best_ask) / 2, 0) * 10000 AS spread_bps, timestampdiff(SECOND, latest_event_time, current_timestamp()) AS age_seconds, CASE WHEN timestampdiff(SECOND, latest_event_time, current_timestamp()) > 5 THEN 'STALE' WHEN best_bid > best_ask THEN 'CROSSED' WHEN best_bid = best_ask THEN 'LOCKED' ELSE 'NORMAL' END AS market_state FROM market_liquidity.gold.top_of_book; Create a five-second depth-imbalance view:
CREATE OR REPLACE VIEW market_liquidity.gold.depth_imbalance AS SELECT window_start, window_end, venue, instrument, SUM(CASE WHEN side = 'BID' THEN observed_quantity ELSE 0 END) AS bid_depth, SUM(CASE WHEN side = 'ASK' THEN observed_quantity ELSE 0 END) AS ask_depth, ( SUM(CASE WHEN side = 'BID' THEN observed_quantity ELSE 0 END) - SUM(CASE WHEN side = 'ASK' THEN observed_quantity ELSE 0 END) ) / NULLIF(SUM(observed_quantity), 0) AS imbalance FROM market_liquidity.silver.windowed_depth GROUP BY window_start, window_end, venue, instrument; Do not interpret imbalance alone. Combine it with spread, absolute depth, event rate, cancellation rate, trade flow, volatility, venue status, and data quality.
Step 8: Estimate executable slippage
Create a parameter table containing representative institutional order sizes:
CREATE TABLE IF NOT EXISTS market_liquidity.reference.order_sizes ( instrument STRING, order_size DECIMAL(24,8), size_label STRING ) USING DELTA; Example size labels can be SMALL, DESK_STANDARD, and STRESS_SIZE. The actual quantities must reflect the instrument contract, desk mandate, and venue liquidity.
For each candidate order size, walk the order-book levels from best to worst price until cumulative quantity reaches the target. Calculate the volume-weighted average execution price.
For a buy order:
buy_slippage_bps = (estimated_vwap - best_ask) / best_ask * 10000
For a sell order:
sell_slippage_bps = (best_bid - estimated_vwap) / best_bid * 10000