The user wants a "streaming join planner" that supports state tiering between SSD (Solid State Drive) and RAM (Random Access Memory).
Key components required:
- Streaming Join Planner: Logic to decide how to execute joins in a streaming context.
- State Tiering: Mechanism to move state between fast memory (RAM) and slower but larger storage (SSD).
- Eviction Policy: Rules for moving data from RAM to SSD (or discarding it).
- Checkpointing: Persisting state for fault tolerance.
- Alerting: Monitoring the system (e.g., state size, latency).
- Tests: Validation of the components.
This is a complex system design and implementation task. I need to provide a comprehensive design and a code structure (likely in Python or Java, but Python is often more accessible for algorithmic prototypes, while Java/Scala is standard for Flink/Spark; I'll use Python for clarity and conceptual demonstration, or maybe a mix if specific libraries are needed, but a pure design + pseudo-code/Python implementation is best).
Architecture/Components Breakdown:
- Core Data Structures:
JoinState: Holds the actual data (keys and values).
TieredStateStore: Manages RAM and SSD interactions.
Planner: Decides join strategies (Hash Join vs. Sort Merge Join, though in streaming it's usually stateful operator logic).
- Tiering Logic:
- Hot Store (RAM): LRU or TTL based.
- Cold Store (SSD): RocksDB-like or file-based storage.
- Swizzling: Moving data between tiers.
- Checkpointing:
- Snapshots of the state.
- Asynchronous barriers (common in streaming).
- Alerting:
- Metrics (Gauges, Counters).
- Thresholds.
Drafting the Implementation Plan:
-
Class Structure:
StateEntry: A wrapper for data.
RAMStore: Dictionary-based with size limits.
SSDStore: Simple file-based simulation.
TieredStateBackend: Orchestrates the tiering.
StreamJoinOperator: The logic performing the join.
EvictionPolicy: The logic deciding what to move.
Checkpointer: Handles saving state.
Monitor: Handles alerting.
-
Detailed Logic:
- State Tiering: When accessing a key, check RAM. If missing, check SSD. If in SSD, promote to RAM. If RAM is full, trigger Eviction.
- Eviction: LRU (Least Recently Used) is standard.
- Checkpointing: For a prototype, just pickle the state to disk. In a real system, this is changelogs or async snapshots. I will implement a simple synchronous snapshot for demonstration.
- Streaming Join: This usually implies a "Window Join" or a "Lookup Join". I'll simulate a Window Join where state is maintained for the duration of the window.
-
Refining the "Planner" Aspect:
The prompt specifically asks for a "planner". In a database context, a planner determines how to execute the query.
- Plan: Should I use RAM or SSD? (Based on estimated state size).
- Plan: Which side of the join to build the hash table for?
- I will create a
StreamingJoinPlanner class that generates a JoinPlan object.
-
Code Implementation (Python):
- Use
dataclasses for structure.
- Use
threading or asyncio for simulating the stream and background checkpointing (though simple synchronous might be safer for a clear demo). Let's stick to synchronous for readability unless async is crucial.
- Use a simple file system abstraction for SSD.
-
Addressing Specific Requirements:
- Eviction Policy: Implement
LRUEvictionPolicy.
- Checkpointing: Implement
save_state and restore_state methods.
- Alerting: A simple callback mechanism if RAM usage > 80%.
- Tests:
pytest style unit tests.
Step-by-Step Construction:
- Step 1: Define the Storage Abstractions. RAM is a dict. SSD is a file (shelve or simple JSON/pickle).
- Step 2: The Tiered Manager. Needs to track access times for LRU.
- Step 3: The Planner. Given a stream schema, it decides: "Windowed Hash Join with Spilling to SSD".
- Step 4: The Operator. The actual loop processing records.
- Step 5: Checkpointing & Alerting. Integrate into the operator loop.
Self-Correction/Refinement during thought process:
- Critique: A full-blown streaming engine (like Flink) is too large for a single code snippet.
- Adjustment: Focus on the core logic of the tiering and join mechanism. Abstract away the network layer and source/sink complexities.
- Focus: The interaction between the Planner (setup) and the Runtime (execution).
Detailed Component Design:
-
TieredStateBackend:
put(key, value): Insert into RAM. If RAM full, evict to SSD.
get(key): Get from RAM. If not, get from SSD and "warm" it (bring to RAM).
evict(): Remove LRU from RAM, write to SSD.
-
StreamingJoinPlanner:
- Inputs: Estimated input rate, state TTL, available RAM.
- Output: Configuration for the Join Operator (e.g., "Use Tiering", "Max RAM 1GB").
-
StreamJoinExecutor:
- Maintains two
TieredStateBackends (left stream and right stream).
- Receives records, updates state, checks for join matches, emits results.
-
Alerting:
- Check RAM usage inside
put or evict.
-
Tests:
- Verify basic join.
- Verify eviction (force RAM limit low).
- Verify retrieval from SSD.
- Verify checkpointing.
Language Choice: Python is best for readability of complex logic like LRU/Hash maps. I will include comments explaining how this maps to production systems (Java/Scala/C++).
Let's structure the response:
- Architecture Overview: Explanation of the design.
- Implementation: The Python code.
- Testing Suite: Unit tests.
- Operational Guide: How to run and monitor.
Self-Correction on "Planner": The user asked for a "Streaming Join Planner". I shouldn't just write an executor. I need a component that plans the join.
- Planner Logic: "If stream A is high volume and Stream B is low volume, keep B in RAM. If A exceeds threshold, spill to SSD."
Let's write the code.
-
Eviction Policy: We need an LRU Cache implementation. Python's OrderedDict is perfect for this.
-
SSD Interface: Since we can't write to actual physical SSD easily in a generic snippet, I will mock the SSD with a disk-backed dictionary (using shelve or just a simplified in-memory dict acting as "Disk" for the test's sake, but I'll add comments for file I/O). Actually, using a temporary file via shelve or sqlite3 makes it "real". sqlite3 is built-in and robust. Let's use sqlite3 for the SSD tier to demonstrate persistence realism.
-
Checkpointing: A checkpoint usually implies saving the current offset and the consistent state. I'll implement a checkpoint_id system.
-
Alerting: A simple AlertManager class that prints warnings.
Structure:
AlertManager
StorageTier (Abstract), RAMTier, SSDTier
EvictionPolicy (LRU)
TieredStateStore (The Manager)
JoinPlanner (Config generator)
StreamJoinOperator (The processor)
TestSuite
Let's refine the Planner.
Input: StreamMetadata (rate, key distribution), HardwareProfile (ram_size, ssd_latency).
Output: JoinConfig (ram_limit, eviction_strategy, join_type).
Okay, ready to generate.
This solution designs a complete Streaming Join Planner & Runtime in Python. It simulates a production-grade system (like Apache Flink or Spark Structured Streaming) but implements the specific logic for State Tiering (RAM ↔ SSD), LRU Eviction, Checkpointing, and Alerting.
1. Architecture Overview
The system consists of four main layers:
- The Planner: Inspects data statistics and determines state configuration (e.g., "Keep hot keys in RAM, overflow to SSD").
- The State Backend: A tiered storage system managing a dictionary (RAM) and a SQLite database (SSD).
- The Join Operator: Processes the stream, joins data, and triggers state management.
- The Monitor: Handles metrics and alerting.
2. Implementation
You will need psutil for memory monitoring (pip install psutil).
import os
import sqlite3
import pickle
import time
import threading
from collections import OrderedDict
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
import random
# --- Configuration & Alerts ---
@dataclass
class Alert:
level: str # INFO, WARNING, CRITICAL
message: str
timestamp: float = field(default_factory=time.time)
class AlertManager:
def __init__(self):
self.alerts = []
def trigger(self, level: str, message: str):
alert = Alert(level, message)
self.alerts.append(alert)
print(f"[ALERT - {level}] {message}")
def get_alerts(self):
return self.alerts
# --- Storage Tiering (RAM & SSD) ---
class TieredStateStore:
def __init__(self, db_path="state_store.db", ram_limit_mb=10):
self.ram_limit_bytes = ram_limit_mb * 1024 * 1024
self.current_ram_usage = 0
# RAM Tier (LRU Cache logic)
self.ram_cache = OrderedDict()
# SSD Tier (Simulated Disk/SSD via SQLite)
self.db_path = db_path
if os.path.exists(db_path):
os.remove(db_path)
self.conn = sqlite3.connect(db_path)
self.cursor = self.conn.cursor()
self._setup_db()
def _setup_db(self):
# Table to store serialized state
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS state_kv (
key TEXT PRIMARY KEY,
value BLOB,
last_access REAL
)
''')
self.conn.commit()
def _estimate_size(self, val):
# Crude estimation of object size in memory
return len(pickle.dumps(val))
def get(self, key: str) -> Optional[Any]:
# 1. Check RAM
if key in self.ram_cache:
self.ram_cache.move_to_end(key) # LRU Touch
return self.ram_cache[key]
# 2. Check SSD
self.cursor.execute("SELECT value FROM state_kv WHERE key = ?", (key,))
row = self.cursor.fetchone()
if row:
val = pickle.loads(row[0])
# Promote to RAM (Read-Through)
self.put(key, val)
return val
return None
def put(self, key: str, value: Any):
val_size = self._estimate_size(value)
# If item is already in RAM, update it
if key in self.ram_cache:
old_val = self.ram_cache[key]
old_size = self._estimate_size(old_val)
self.current_ram_usage -= old_size
self.ram_cache[key] = value
self.ram_cache.move_to_end(key)
self.current_ram_usage += val_size
return
# Eviction Policy: Make room if necessary
while (self.current_ram_usage + val_size) > self.ram_limit_bytes and len(self.ram_cache) > 0:
self._evict_one()
# Add to RAM
self.ram_cache[key] = value
self.current_ram_usage += val_size
def _evict_one(self):
# Evict Least Recently Used (FIFO from OrderedDict)
key, val = self.ram_cache.popitem(last=False)
val_size = self._estimate_size(val)
self.current_ram_usage -= val_size
# Write to SSD (Write-Through on eviction)
self._write_to_ssd(key, val)
def _write_to_ssd(self, key, val):
blob = pickle.dumps(val)
self.cursor.execute(
"INSERT OR REPLACE INTO state_kv (key, value, last_access) VALUES (?, ?, ?)",
(key, blob, time.time())
)
self.conn.commit()
def flush(self):
# Move everything to SSD for clean shutdown
for k, v in list(self.ram_cache.items()):
self._write_to_ssd(k, v)
self.ram_cache.clear()
self.current_ram_usage = 0
def close(self):
self.flush()
self.conn.close()
# --- Planner & Checkpointing ---
class StreamingJoinPlanner:
"""
Decides how the join should be executed based on available resources.
"""
def __init__(self, ram_available_mb):
self.ram_available_mb = ram_available_mb
def plan(self) -> Dict:
# In a real system, this would estimate state size based on input rates and retention time
# Here we decide to allocate 80% of available RAM to the state buffer
return {
"ram_limit_mb": self.ram_available_mb * 0.8,
"join_strategy": "HASH_JOIN_TIERED",
"retention_seconds": 3600
}
class CheckpointManager:
def __init__(self, state_store: TieredStateStore):
self.state_store = state_store
self.checkpoint_id = 0
def trigger_checkpoint(self):
start = time.time()
# In a real system, this would block inputs or use copy-on-write
self.state_store.flush()
duration = time.time() - start
self.checkpoint_id += 1
return {"id": self.checkpoint_id, "duration": duration}
# --- The Join Operator ---
class StreamJoinOperator:
def __init__(self, state_store: TieredStateStore, alert_manager: AlertManager):
self.state = state_store
self.alerts = alert_manager
def process(self, stream_name: str, record: Dict):
"""
Simulates a simple inner join logic.
Stream A waits for Stream B and vice versa.
"""
key = record['id']
current_state = self.state.get(key) or {"stream_a": None, "stream_b": None}
# Join Logic
if stream_name == "A":
current_state['stream_a'] = record
else:
current_state['stream_b'] = record
# Check if join condition met
if current_state['stream_a'] and current_state['stream_b']:
# Emit Result
result = {
"id": key,
"data_a": current_state['stream_a']['data'],
"data_b": current_state['stream_b']['data']
}
# State Cleanup (TTL/Match removal)
self.state.delete(key) # (Implementation of delete omitted for brevity in Store)
# Alert on Match
self.alerts.trigger("INFO", f"Joined record {key}")
return result
# Update State
self.state.put(key, current_state)
# Check for memory pressure alerts
usage_pct = (self.state.current_ram_usage / self.state.ram_limit_bytes) * 100
if usage_pct > 90:
self.alerts.trigger("WARNING", f"Memory pressure high: {usage_pct:.2f}%")
return None
# --- Tests ---
import unittest
class TestStreamingTiering(unittest.TestCase):
def setUp(self):
self.alerts = AlertManager()
# Very small limit (1KB) to force eviction immediately
self.store = TieredStateStore(ram_limit_mb=0.001, db_path="test_state.db")
self.join_op = StreamJoinOperator(self.store, self.alerts)
def test_basic_join(self):
rec_a = {'id': '1', 'data': 'valueA'}
rec_b = {'id': '1', 'data': 'valueB'}
res1 = self.join_op.process("A", rec_a)
self.assertIsNone(res1) # Not joined yet
res2 = self.join_op.process("B", rec_b)
self.assertIsNotNone(res2)
self.assertEqual(res2['data_a'], 'valueA')
def test_tiering_and_eviction(self):
# Create a record large enough to trigger eviction of previous records
big_rec_1 = {'id': '1', 'data': "x" * 200}
big_rec_2 = {'id': '2', 'data': "y" * 200}
big_rec_3 = {'id': '3', 'data': "z" * 200}
# Put 1
self.join_op.process("A", big_rec_1)
self.assertIn('1', self.store.ram_cache)
# Put 2 (Should evict 1)
self.join_op.process("A", big_rec_2)
self.assertNotIn('1', self.store.ram_cache) # 1 evicted from RAM
self.assertIn('2', self.store.ram_cache) # 2 in RAM
# Verify 1 is on SSD
val_1 = self.store.get('1')
self.assertIsNotNone(val_1)
# Upon reading 1, it is promoted back to RAM. 2 should be evicted.
self.assertIn('1', self.store.ram_cache)
def test_alerts(self):
# Spam data to trigger memory warning
for i in range(10):
self.join_op.process("A", {'id': str(i), 'data': "z" * 200})
warnings = [a for a in self.alerts.get_alerts() if a.level == "WARNING"]
self.assertTrue(len(warnings) > 0)
def test_checkpointing(self):
chkpt_mgr = CheckpointManager(self.store)
self.join_op.process("A", {'id': '100', 'data': 'persistent'})
meta = chkpt_mgr.trigger_checkpoint()
self.assertTrue(meta['duration'] >= 0)
# Verify SSD content directly
self.store.cursor.execute("SELECT key FROM state_kv WHERE key='100'")
row = self.store.cursor.fetchone()
self.assertIsNotNone(row)
def tearDown(self):
self.store.close()
if os.path.exists("test_state.db"):
os.remove("test_state.db")
if __name__ == "__main__":
# 1. Plan the join
planner = StreamingJoinPlanner(ram_available_mb=64)
plan = planner.plan()
print(f"Execution Plan: {plan}")
# 2. Run Tests
unittest.main(argv=['first-arg-is-ignored'], exit=False)
3. Detailed Component Breakdown
1. The Planner (StreamingJoinPlanner)
This component represents the "Brain" before the execution starts. In a real system (like Flink SQL), the planner would look at statistics.
- Logic: It decides the
ram_limit_mb. If the user requests a 100GB state but has 1GB RAM, it configures the operator to rely heavily on disk. Here, we set it to 80% of available memory to leave headroom for processing.
2. State Tiering & Eviction (TieredStateStore)
This is the core "Tiered Storage" engine.
- RAM Tier: Uses
collections.OrderedDict. This allows O(1) access and maintains insertion order. When move_to_end(key) is called, it implements LRU (Least Recently Used) logic.
- SSD Tier: Uses SQLite (acting as RocksDB). It persists binary blobs (
BLOB).
- Eviction Policy: When
put() is called, if current_ram_usage > ram_limit, we pop the first item of the dictionary (the LRU item) and write it to SQLite.
- Read-Through: If
get() misses RAM, it checks SQLite. If found, it puts it back into RAM (promoting "hot" data) and evicts something else.
3. Checkpointing (CheckpointManager)
Streaming jobs are long-running and fail. We need to save state.
- Implementation:
trigger_checkpoint() simply calls flush(). This forces all dirty data from RAM to the SSD/Disk.
- Production Note: In a real system, this would use Asynchronous Barrier Snapshotting (based on Chandy-Lamport) to not halt the stream completely.
4. Alerting (AlertManager)
- Integration: The
StreamJoinOperator calculates memory usage percentage.
- Policy: If usage > 90%, it fires a
WARNING alert. In a real scenario, this would hook into Prometheus or CloudWatch.
5. Tests
The test suite verifies:
- Correctness: Does the join actually happen?
- Tiering: Does data move to SSD when RAM is full?
- Promotion: Does accessing data on SSD bring it back to RAM?
- Checkpointing: Does the flush actually write to the SQLite DB?