We are going to design a streaming join planner that uses two tiers of state: RAM (fast, small) and SSD (slower, large).
The idea is to keep the most recently accessed or important join state in RAM and evict less important to SSD.
We need to consider:
- State partitioning: Since it's a streaming join, we might have partitioned state (e.g., by key) to scale.
- Eviction policy: When RAM is full, we need to decide which partition to evict to SSD.
- Checkpointing: Periodically, we checkpoint the state (both RAM and SSD) to durable storage for fault tolerance.
- Alerting: We need to monitor and alert on conditions such as high eviction rate, low hit rate, or checkpoint failures.
- Tests: Unit and integration tests for the planner.
Steps:
-
Define the state manager that will manage two tiers: RAM and SSD.
- We assume that the state is partitioned by key (or key range) and each partition is a chunk of data.
- We will have an in-memory map (or cache) for RAM and a disk-based storage for SSD.
-
Eviction policy:
- We can use an LRU (Least Recently Used) or LFU (Least Frequently Used) policy for RAM.
- When a partition is evicted from RAM, we write it to SSD (if not already there) and then remove from RAM.
- When a partition is accessed and it's on SSD, we bring it back to RAM (if there's space, otherwise we evict another).
-
Checkpointing:
- We periodically take a snapshot of the state (both RAM and SSD) and write to a durable store (like HDFS or S3).
- We need to track which partitions have been checkpointed and which are dirty (modified since last checkpoint).
-
Alerting:
- Monitor metrics: eviction rate, hit rate (RAM vs SSD), checkpoint duration, etc.
- Set up alerts for thresholds (e.g., eviction rate > X, checkpoint fails, etc.)
-
Tests:
- Unit tests for the state manager (eviction, load, save, checkpoint).
- Integration test with a streaming job that uses the planner and simulate failures.
Implementation plan:
We'll design a class TieredStateManager that has:
ram_state: a map from partition id to the partition data (in memory)
ssd_state: a map from partition id to the partition data (on disk, but we might cache some in memory? No, SSD is the backing store and we only bring to RAM on access)
partition_metadata: a structure that tracks for each partition:
last_access_time: for LRU
access_count: for LFU (if we want to use LFU)
is_dirty: whether the partition in RAM has been modified and not yet persisted to SSD (or checkpointed)
on_ssd: whether the partition is currently stored on SSD (so that we don't write again if evicted and then reloaded without modification)
We'll use a combination of LRU and a dirty flag. We might also consider a write-back or write-through policy.
For simplicity, let's assume:
- When a partition is updated, it's in RAM and marked dirty.
- When we evict a dirty partition, we write it to SSD (so that SSD has the latest) and then remove from RAM.
- When we load a partition from SSD (because it's not in RAM) we bring it to RAM and mark it as not dirty (because SSD has the latest).
But note: if we have multiple updates to the same partition, we don't want to write to SSD on every update. So we mark dirty and write only on eviction or checkpoint.
Checkpointing:
- We want to checkpoint all partitions (both RAM and SSD) to a durable store. But note that if a partition is only on SSD and not in RAM, we can checkpoint the SSD version.
- However, if a partition is in RAM and dirty, then the SSD version might be stale. So during checkpoint, we must ensure that we checkpoint the latest version.
- We can have two options:
a) Write all dirty partitions from RAM to SSD before checkpointing (so that SSD has the latest) and then checkpoint from SSD.
b) Checkpoint from RAM for dirty partitions and from SSD for non-dirty ones? But then we have two sources.
Let's do:
- During checkpoint, we first flush all dirty partitions from RAM to SSD (so that SSD is up to date) and then checkpoint from SSD.
- Alternatively, we can checkpoint directly from RAM for dirty ones and from SSD for non-dirty ones, but then we have to make sure that we don't have a partition both in RAM (dirty) and on SSD (stale). We can invalidate the SSD copy when we have a dirty RAM copy? That might be complex.
Simpler: We maintain that the SSD is the source of truth for non-dirty partitions, and for dirty ones we have only in RAM. Then during checkpoint, we write the dirty ones to SSD and then checkpoint from SSD.
Steps for checkpoint:
1. For each partition in RAM that is dirty, write it to SSD (overwrite the existing one if present, or create new).
2. Then, take a snapshot of the entire SSD state (maybe by copying the SSD directory or using a snapshot mechanism) and mark that as the checkpoint.
But note: during step 1, if the job is running, we might be updating partitions. We need to lock the partition during write? Or use copy-on-write?
Alternatively, we can do:
We have a global atomic swap of the state? Not easy.
Let's think about consistency:
We want the checkpoint to be a consistent snapshot of the state at a point in time.
We can use a two-phase approach:
Phase 1: Flush all dirty partitions from RAM to SSD. While doing so, we lock each partition (so that no updates during flush) or we use a versioning system.
But locking each partition might be heavy and cause backpressure.
Another idea: We can use a write-ahead log (WAL) for updates, but that's another layer.
Given the complexity, let's assume:
We are going to have a background thread that periodically checkpoints.
Steps for the checkpoint thread:
1. Stop accepting new updates? No, that would halt the stream.
2. We can use a copy-on-write for each partition:
- When we update a partition in RAM, we mark the old version as immutable and create a new version? That's heavy.
3. Alternatively, we can have a global mutex for the entire state during checkpoint? That would halt all updates, which is not acceptable for high throughput.
Given the constraints, we might need to accept that the checkpoint is not a perfect snapshot, but we can do:
- We checkpoint the state as it is at the moment we start the checkpoint, but then updates that happen during checkpoint might be lost? Not acceptable.
So we need a way to get a consistent snapshot without stopping the world.
One common approach in streaming systems is to use a barrier (like in Flink) that stops the processing of events until the checkpoint is done, but that's heavy.
Alternatively, we can use asynchronous checkpointing with versioning:
- Each partition in RAM has a version number.
- When we update, we increment the version and write the new data.
- When we checkpoint, we note the current version for each partition and then read the partition with that version. But if the partition is being updated, we might read an old version? We need to lock the version.
This is getting complex.
Given the time, let's simplify:
We assume that the state is updated in a single thread (or we have a single writer per partition) and we can do:
- For each partition, we have a lock (or we use a concurrent data structure that allows snapshot).
- During checkpoint, we lock each partition (in some order to avoid deadlock) and then copy the current state to a temporary structure, then release.
But then we are blocking updates for the duration of the checkpoint for each partition.
Alternatively, we can use a copy-on-write for each partition:
- We have a current pointer to the partition data. When updating, we create a new copy and update the pointer (atomic operation). Then the old copy can be checkpointed.
This is how many systems do it (like copy-on-write in databases).
Steps:
- Each partition in RAM is represented by an immutable data structure (or we treat it as immutable after creation).
- When we update, we create a new version and atomically swap the pointer.
- The old version is still available for checkpoint.
Then checkpoint can read the current pointer without locking, because the pointer is atomic and the old version is immutable.
But note: we are storing the partition in RAM and we don't want to keep multiple versions forever. We can garbage collect old versions that are no longer in use.
How do we know when an old version is no longer in use?
- We have a reference count? Or we wait until the checkpoint that used it is done.
We can have:
- For each partition, we keep the current version and a list of old versions that are being used by ongoing checkpoints.
This is getting very complex.
Given the scope, let's assume we are allowed to pause the updates for the duration of the checkpoint? That might be acceptable for low throughput.
But the requirement says "streaming", so we want low latency.
Let's change the design:
We will have two state managers:
- One for RAM (in-memory map) and one for SSD (disk-based).
- The RAM state is the primary for updates, and we asynchronously write to SSD (either on eviction or periodically).
- Checkpointing:
We want to checkpoint the entire state (both RAM and SSD) at a consistent point.
We can do:
1. Stop the world (pause processing) for a short time.
2. Flush all dirty partitions from RAM to SSD (so that SSD is up to date).
3. Take a snapshot of the SSD (by copying the directory or using a snapshot feature of the file system).
4. Resume processing.
This is similar to how many databases do checkpoint.
The pause time should be minimal if we have few dirty partitions and fast SSD.
But if we have a lot of dirty partitions, the pause might be long.
Alternatively, we can do:
- We have a background thread that continuously writes dirty partitions to SSD (so that SSD is always almost up to date). Then during checkpoint, we only need to flush the very recent ones.
Let's do:
- We have a background flusher that wakes up every X seconds and flushes dirty partitions from RAM to SSD (if any). Then during checkpoint, we only need to flush the ones that became dirty after the last flush.
But then we have two flushes: the background and the checkpoint. We need to coordinate.
Alternatively, we can rely only on the checkpoint to flush? Then we might have a lot of dirty partitions in RAM and the checkpoint pause might be long.
Let's stick to:
- We have a background flusher that runs every `flush_interval` and flushes all dirty partitions.
- During checkpoint, we don't flush, we just take a snapshot of the SSD (which should be up to date because of the background flusher). But what if a partition was updated right after the background flush and before the checkpoint? Then it's dirty in RAM and not on SSD.
So we still need to flush during checkpoint? Or we can note that the checkpoint is not consistent? We want consistency.
We can do:
- The checkpoint barrier stops the processing (so no new updates) and then we wait for the background flusher to finish (or we flush the remaining dirty ones) and then take the snapshot.
But the background flusher might take a while.
Alternatively, we can have the checkpoint do the flushing for the remaining dirty ones and then take the snapshot.
Steps for checkpoint:
1. Stop processing (or wait for a barrier that stops the processing of events).
2. Flush all dirty partitions from RAM to SSD (this is the same as the background flusher but we do it synchronously for all).
3. Take a snapshot of the SSD (which now has all the updates).
4. Resume processing.
This ensures consistency.
The downside: the stop-the-world time is the time to flush all dirty partitions.
We can try to minimize the dirty partitions by having the background flusher run frequently.
We can also have the background flusher run and then during checkpoint we only flush the ones that became dirty after the background flush started? That's complex.
Let's keep it simple: checkpoint does the flush.
Given the complexity, we might decide that for the prototype, we do:
- No background flusher. We flush only on eviction and on checkpoint.
- Eviction: when we evict a dirty partition, we write it to SSD.
- Checkpoint: we flush all dirty partitions (including those that are not evicted) and then take a snapshot.
This way, the SSD is eventually consistent, but at checkpoint time we make it consistent.
But note: if a partition is dirty and not evicted, it's only in RAM. Then during checkpoint we flush it.
So the steps for checkpoint:
For each partition in RAM:
if dirty, write to SSD (overwrite if exists) and mark as not dirty.
Then take a snapshot of the entire SSD (by copying the directory or using a file system snapshot).
We need to lock the entire state during this? We can lock per partition? But then we might have a partition being updated while we are flushing.
We need to lock during the flush of each partition? We can do:
For each partition in RAM (in some order, to avoid deadlock, we can order by partition id):
lock(partition)
if dirty, write to SSD and mark not dirty.
unlock(partition)
Then we have a point where all dirty partitions are on SSD, but note: a partition might be updated after we unlocked it? Then it becomes dirty again and we didn't flush it.
So we need to have a global lock? Or we need to repeat until no dirty partitions?
Alternatively, we can do:
We have a global checkpoint lock that we take at the beginning and release at the end.
But that stops all updates for the entire checkpoint.
Given the time, let's assume we can take a global lock for the checkpoint. This is acceptable for low throughput.
Steps:
global_lock.lock()
for each partition in RAM:
if dirty, write to SSD and mark not dirty.
take_snapshot_of_SSD()
global_lock.unlock()
This ensures consistency.
However, in a real system, we would want to avoid the global lock.
Given the complexity, we will design for the prototype with a global lock during checkpoint.
-
Alerting:
We'll expose metrics:
- `eviction_count`: total number of evictions.
- `ram_hit_count`: number of times a partition was found in RAM.
- `ssd_hit_count`: number of times a partition was found in SSD and then loaded to RAM.
- `checkpoint_duration`: time taken for checkpoint.
- `dirty_partition_count`: number of dirty partitions at the start of checkpoint.
We can set up alerts:
- If `eviction_count` increases rapidly, we might need more RAM.
- If `ssd_hit_count` is high, we might need more RAM or better eviction policy.
- If `checkpoint_duration` is too long, we might need to optimize the flush or have more frequent background flushes.
-
Tests:
We'll write:
- Unit tests for the state manager (with a fixed RAM size, test eviction, load, flush, checkpoint).
- Integration test: simulate a streaming join with the state manager, and then kill the job and restore from checkpoint.
Implementation:
Let's define:
class Partition:
id: str
data: bytes # or whatever the join state is (could be a more complex structure)
class TieredStateManager:
def __init__(self, ram_capacity, ssd_path):
self.ram_capacity = ram_capacity # in bytes or number of partitions?
self.ssd_path = ssd_path
self.ram = OrderedDict() # for LRU, key: partition_id, value: (Partition, is_dirty)
self.ssd = {} # key: partition_id, value: path to the file on disk? or we store the data? We'll store the data in memory for the prototype? No, SSD should be on disk.
Actually, for SSD we want to store on disk. But for simplicity in prototype, we might store in memory? No, we want to test eviction to disk.
Let's assume:
RAM: stores the entire partition data in memory.
SSD: we store each partition as a file in `ssd_path` with the partition id as the file name.
So:
self.ram: OrderedDict from partition_id to (data, is_dirty)
self.ssd: we don't keep an in-memory map for SSD, we just write to disk and read from disk when needed.
But we need to know which partitions are on SSD? We can check if the file exists? That might be expensive.
Alternatively, we keep a set of partition ids that are on SSD.
Let's do:
self.ssd_index = set() # set of partition ids that are stored on SSD.
def get_partition(self, partition_id):
if partition_id in self.ram:
# move to end for LRU
self.ram.move_to_end(partition_id)
return self.ram[partition_id][0]
elif partition_id in self.ssd_index:
# load from SSD to RAM
data = self._load_from_ssd(partition_id)
self._add_to_ram(partition_id, data, dirty=False)
return data
else:
raise KeyError(f"Partition {partition_id} not found")
def update_partition(self, partition_id, new_data):
# This is called when we update the partition (e.g., adding a new key-value)
if partition_id in self.ram:
old_data, _ = self.ram[partition_id]
# We assume we are replacing the entire partition? Or updating?
# For simplicity, we replace.
self.ram[partition_id] = (new_data, True)
self.ram.move_to_end(partition_id)
else:
# Not in RAM, so we need to load from SSD (if exists) and then update?
# But note: the update might be for a new partition that doesn't exist.
# Let's assume we are doing upsert.
# If it's on SSD, we load and then update.
if partition_id in self.ssd_index:
data = self._load_from_ssd(partition_id)
self._add_to_ram(partition_id, data, dirty=False) # then we update below
else:
# new partition, so we just add to RAM
self._add_to_ram(partition_id, new_data, dirty=True)
return
# Now it's in RAM, so update
self.ram[partition_id] = (new_data, True)
# After update, check if we need to evict
self._evict_if_needed()
def _add_to_ram(self, partition_id, data, dirty):
self.ram[partition_id] = (data, dirty)
self.ram.move_to_end(partition_id)
def _evict_if_needed(self):
# We assume ram_capacity is the maximum number of partitions in RAM? Or by size?
# For simplicity, let's assume by number of partitions.
while len(self.ram) > self.ram_capacity:
# Evict the least recently used (first item in OrderedDict)
partition_id, (data, is_dirty) = self.ram.popitem(last=False)
if is_dirty:
self._write_to_ssd(partition_id, data)
self.ssd_index.add(partition_id)
def _write_to_ssd(self, partition_id, data):
path = os.path.join(self.ssd_path, partition_id)
with open(path, 'wb') as f:
f.write(data)
def _load_from_ssd(self, partition_id):
path = os.path.join(self.ssd_path, partition_id)
with open(path, 'rb') as f:
return f.read()
def checkpoint(self):
# This is called by the checkpoint thread.
with self.global_lock:
# Flush all dirty partitions to SSD
for partition_id, (data, is_dirty) in list(self.ram.items()):
if is_dirty:
self._write_to_ssd(partition_id, data)
self.ram[partition_id] = (data, False) # mark as not dirty
# Now take a snapshot of the SSD.
# We can just copy the entire ssd_path to a checkpoint directory.
checkpoint_dir = f"{self.ssd_path}_checkpoint_{int(time.time())}"
shutil.copytree(self.ssd_path, checkpoint_dir)
# We might want to clean up old checkpoints? That's another topic.
def get_metrics(self):
return {
'ram_size': len(self.ram),
'ssd_index_size': len(self.ssd_index),
'eviction_count': self.eviction_count, # we need to track this
'ram_hit_count': self.ram_hit_count,
'ssd_hit_count': self.ssd_hit_count,
}
This is a simplified version.
We need to track:
self.eviction_count = 0
self.ram_hit_count = 0
self.ssd_hit_count = 0
And update in get_partition and _evict_if_needed.
Also, we need to handle concurrent access? We are using a global lock for checkpoint, but for normal operations we are not locking.
This is not thread-safe. We need to decide if we are going to support multi-threaded access.
For simplicity, let's assume single-threaded access (the stream operator is single-threaded).
If we want multi-threaded, we need to add locks for each partition or use a concurrent map.
Given the time, we assume single-threaded.
-
Alerting:
We can have a separate thread that collects metrics and sends alerts if thresholds are crossed.
-
Tests:
We'll write:
test_eviction: fill RAM beyond capacity and check that the least recently used is evicted.
test_flush: update a partition, then checkpoint, and check that the file is on SSD.
test_restore: after checkpoint, we can create a new state manager and load from the checkpoint directory? But our current design doesn't support loading from checkpoint.
We need to add:
def restore_from_checkpoint(checkpoint_dir):
# create a new state manager and load all partitions from the checkpoint_dir into RAM? Or into SSD?
# We want to restore the state as it was at the checkpoint.
We can do:
- Create a new state manager with the same ram_capacity and a new ssd_path? Or we can restore to the same ssd_path?
Actually, in a real system, we would restore from the checkpoint by loading the state from the checkpoint directory into the state manager.
We need a method to load all partitions from a directory (which is a checkpoint) into the state manager.
But note: the checkpoint is a snapshot of the SSD at a point in time. So we can:
- Clear the current state (RAM and SSD index) and then load all files from the checkpoint directory into SSD (by copying the files to the current ssd_path? or just point to the checkpoint directory?).
However, in our design, the SSD is a directory that we write to. We can have:
- The state manager is initialized with an ssd_path. We can have a flag that says we are restoring.
Alternatively, we can have a separate method to load from a checkpoint:
def load_from_checkpoint(self, checkpoint_dir):
# For each file in checkpoint_dir, copy to self.ssd_path and add to self.ssd_index.
# Then, we don't load any into RAM? Or we can load all? That might exceed RAM.
# We want to start with an empty RAM and the SSD having all the partitions.
So:
- We copy all files from checkpoint_dir to self.ssd_path.
- We list all partition ids from the files and add to self.ssd_index.
Then, when we access a partition, it will be loaded from SSD to RAM.
But note: the checkpoint might have many partitions, and we might not want to load them all at once.
So we just set the SSD index and leave RAM empty.
Steps:
for filename in os.listdir(checkpoint_dir):
partition_id = filename # assuming filename is the partition id
src = os.path.join(checkpoint_dir, partition_id)
dst = os.path.join(self.ssd_path, partition_id)
shutil.copyfile(src, dst)
self.ssd_index.add(partition_id)
Then, when we get_partition for a partition_id, it will be loaded from SSD.
This seems workable.
Let's code accordingly.
However, note: the checkpoint we took is a copy of the SSD at that time. But after checkpoint, we continue processing and might have updated some partitions (in RAM and then evicted to SSD). So the SSD is changing.
So when we restore, we want the state as of the checkpoint, not the current SSD.
Therefore, we should not overwrite the current SSD with the checkpoint? Actually, we are restoring from a checkpoint, meaning we are starting a new job from that checkpoint.
So we can:
- Start a new state manager with an empty SSD and RAM.
- Then load the checkpoint into the SSD of the new state manager.
Or we can have:
- The state manager is created with a checkpoint directory. Then we load from that checkpoint and set the SSD to be the checkpoint directory? But then we are writing new updates to the same directory? That would mix the checkpoint and new updates.
We want to separate the checkpoint (which is read-only) and the current state.
So we should:
- Have a current SSD directory (where we write updates) and a checkpoint directory (which is a snapshot).
- When we restore, we start a new job and we set the current SSD to be a copy of the checkpoint? Or we start with an empty SSD and then load the checkpoint into RAM? But then we lose the SSD tier?
Actually, the checkpoint includes the entire state (both RAM and SSD) at that time? In our design, the checkpoint is a snapshot of the SSD (which should be up to date because we flushed all dirty partitions). So the checkpoint is the entire state.
So we can:
- When restoring, we set the SSD of the new state manager to be the checkpoint directory? But then we need to write updates to a different directory.
We need two directories:
- current_ssd_path: where we write the current state (for durability and for future checkpoints).
- checkpoint_dir: a read-only snapshot.
But in our current design, we only have one ssd_path.
We can change:
- The state manager has:
current_ssd_path: where we write the current state.
checkpoint_dir: optional, if provided, we load from there at startup.
- At startup, if checkpoint_dir is provided, we load all partitions from checkpoint_dir into current_ssd_path (copy) and set the ssd_index accordingly.
- Then we start with the current_ssd_path having the state and RAM empty.
So:
def __init__(self, ram_capacity, current_ssd_path, checkpoint_dir=None):
self.ram_capacity = ram_capacity
self.current_ssd_path = current_ssd_path
self.ram = OrderedDict()
self.ssd_index = set()
if checkpoint_dir:
self._load_from_checkpoint(checkpoint_dir)
def _load_from_checkpoint(self, checkpoint_dir):
for filename in os.listdir(checkpoint_dir):
src = os.path.join(checkpoint_dir, filename)
dst = os.path.join(self.current_ssd_path, filename)
shutil.copyfile(src, dst)
self.ssd_index.add(filename)
Then, when we write to SSD, we write to current_ssd_path.
And when we checkpoint, we copy from current_ssd_path to a new checkpoint directory.
This way, we separate the current state and the checkpoint.
But note: the checkpoint we take is a copy of the current_ssd_path. And we restore from a checkpoint by copying it to a new current_ssd_path.
This is acceptable.
Let's adjust the checkpoint method:
def checkpoint(self, checkpoint_dir):
# First, flush all dirty partitions to current_ssd_path (with global lock)
with self.global_lock:
for partition_id, (data, is_dirty) in list(self.ram.items()):
if is_dirty:
self._write_to_ssd(partition_id, data) # writes to current_ssd_path
self.ram[partition_id] = (data, False)
# Now, copy the entire current_ssd_path to checkpoint_dir
if os.path.exists(checkpoint_dir):
shutil.rmtree(checkpoint_dir)
shutil.copytree(self.current_ssd_path, checkpoint_dir)
And the restore:
We create a new state manager and pass the checkpoint_dir.
However, note that when we restore, we are starting a new job. We might want to continue from the checkpoint, so we set the current_ssd_path to a new directory (or the same?).
We can have:
- The job is configured with a base directory for state.
- When starting, we look for the latest checkpoint in that base directory and then set:
current_ssd_path = base_dir / "current"
checkpoint_dir = base_dir / "checkpoints" / latest
Then we copy the checkpoint to current_ssd_path and start.
This is a common pattern.
We'll leave the details of the checkpoint directory management to the caller.
So the state manager just:
- At init: if checkpoint_dir is provided, copy all files from checkpoint_dir to current_ssd_path and add to ssd_index.
- During operation: read/write to current_ssd_path.
- When checkpointing: copy current_ssd_path to a given checkpoint_dir.
This design.
Let's code accordingly.
We'll also need to handle:
- What if the current_ssd_path doesn't exist? We create it.
Steps in init:
if not os.path.exists(self.current_ssd_path):
os.makedirs(self.current_ssd_path)
if checkpoint_dir:
self._load_from_checkpoint(checkpoint_dir)
Now, let's write the code with these ideas.
We'll also add:
- Metrics.
- A background thread for checkpointing? Or the caller will call checkpoint periodically.
We'll let the caller schedule the checkpoint.
We'll also add:
- An eviction policy that can be configured (LRU by default).
But for simplicity, we'll stick to LRU.
Let's code.
Note: This is a prototype and not production-ready. We are skipping many details (like error handling, file system issues, etc.)
We'll write the code in a single file for now.
We'll also write tests using pytest.
Let's create:
tiered_state_manager.py
And then test_tiered_state_manager.py
We'll also simulate a streaming join that uses this state manager.
But note: the streaming join planner is the one that uses the state manager. We are building the state manager.
The planner would decide which partitions to keep in RAM and which to evict, but that's exactly what the state manager does.
So the state manager is the core.
Let's code accordingly.
I'll design a comprehensive streaming join planner with state tiering between RAM and SSD. This is a complex system, so I'll provide a structured implementation with all requested features.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Streaming Join Planner │
├─────────────┬─────────────┬─────────────┬───────────────┤
│ Router │ RAM Tier │ SSD Tier │ Checkpointing │
│ (Key Hash) │ (LRU Cache) │ (Write-Back)│ & Recovery │
├─────────────┴─────────────┴─────────────┴───────────────┤
│ Eviction Policy & Alerting System │
└─────────────────────────────────────────────────────────────┘
1. Core Implementation
import asyncio
import hashlib
import heapq
import json
import logging
import os
import pickle
import shutil
import threading
import time
from collections import OrderedDict, defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple
import mmap
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
@dataclass
class PartitionMetadata:
"""Metadata for a state partition"""
partition_id: str
size_bytes: int
last_access: float
access_count: int = 0
is_dirty: bool = False
is_pinned: bool = False # Prevent eviction
created_at: float = field(default_factory=time.time)
last_modified: float = field(default_factory=time.time)
@dataclass
class CheckpointMetadata:
"""Checkpoint metadata"""
checkpoint_id: str
timestamp: float
partitions: Set[str]
size_bytes: int
path: str
is_complete: bool = False
class LRUEvictionPolicy:
"""LRU eviction policy with access frequency weighting"""
def __init__(self, ram_capacity_bytes: int):
self.ram_capacity = ram_capacity_bytes
self.current_usage = 0
self.access_log = [] # (partition_id, timestamp, size)
def should_evict(self, new_partition_size: int) -> List[str]:
"""Determine which partitions to evict to make room"""
if self.current_usage + new_partition_size <= self.ram_capacity:
return []
needed = self.current_usage + new_partition_size - self.ram_capacity
candidates = []
# Simple LRU: find oldest accessed partitions
for partition_id, _, size in sorted(self.access_log, key=lambda x: x[1]):
if size <= needed:
candidates.append(partition_id)
needed -= size
if needed <= 0:
break
return candidates
def record_access(self, partition_id: str, size: int):
"""Record partition access"""
self.access_log.append((partition_id, time.time(), size))
# Keep only recent accesses (e.g., last 10000)
if len(self.access_log) > 10000:
self.access_log = self.access_log[-5000:]
class TieredStateManager:
"""Manages state tiering between RAM and SSD"""
def __init__(
self,
ram_capacity_bytes: int = 10 * 1024 * 1024 * 1024, # 10GB
ssd_path: str = "/var/lib/streaming/state",
checkpoint_path: str = "/var/lib/streaming/checkpoints",
eviction_policy: str = "lru",
wal_enabled: bool = True
):
self.ram_capacity = ram_capacity_bytes
self.ssd_path = Path(ssd_path)
self.checkpoint_path = Path(checkpoint_path)
self.wal_enabled = wal_enabled
# Create directories
self.ssd_path.mkdir(parents=True, exist_ok=True)
self.checkpoint_path.mkdir(parents=True, exist_ok=True)
# State storage
self.ram_state: OrderedDict[str, Any] = OrderedDict() # LRU cache
self.ram_metadata: Dict[str, PartitionMetadata] = {}
self.ssd_index: Dict[str, PartitionMetadata] = {} # Tracks what's on SSD
self.wal: List[Dict] = [] # Write-ahead log
# Policies
self.eviction_policy = LRUEvictionPolicy(ram_capacity_bytes)
# Locks
self.ram_lock = threading.RLock()
self.ssd_lock = threading.RLock()
self.checkpoint_lock = threading.RLock()
# Metrics
self.metrics = {
'ram_hits': 0,
'ssd_hits': 0,
'evictions': 0,
'checkpoints': 0,
'wal_size': 0,
'ram_usage': 0,
'ssd_usage': 0
}
self.metrics_lock = threading.Lock()
# Background tasks
self.running = True
self.checkpoint_interval = 300 # 5 minutes
self.wal_flush_interval = 60 # 1 minute
# Start background threads
self.checkpoint_thread = threading.Thread(
target=self._checkpoint_worker,
daemon=True
)
self.wal_thread = threading.Thread(
target=self._wal_flush_worker,
daemon=True
)
self.alert_thread = threading.Thread(
target=self._alert_worker,
daemon=True
)
def start(self):
"""Start background workers"""
self.checkpoint_thread.start()
self.wal_thread.start()
self.alert_thread.start()
logger.info("TieredStateManager started")
def stop(self):
"""Graceful shutdown"""
self.running = False
self.checkpoint_thread.join(timeout=10)
self.wal_thread.join(timeout=10)
self._flush_wal() # Final WAL flush
logger.info("TieredStateManager stopped")
def get_partition(self, partition_id: str) -> Optional[Any]:
"""Get partition from RAM or SSD"""
with self.ram_lock:
if partition_id in self.ram_state:
# RAM hit - move to end (LRU)
self.ram_state.move_to_end(partition_id)
metadata = self.ram_metadata[partition_id]
metadata.last_access = time.time()
metadata.access_count += 1
with self.metrics_lock:
self.metrics['ram_hits'] += 1
return self.ram_state[partition_id]
# RAM miss, try SSD
with self.ssd_lock:
if partition_id in self.ssd_index:
# Load from SSD to RAM
data = self._load_from_ssd(partition_id)
self._add_to_ram(partition_id, data, dirty=False)
with self.metrics_lock:
self.metrics['ssd_hits'] += 1
return data
return None
def put_partition(self, partition_id: str, data: Any, pin: bool = False):
"""Store partition in RAM (with optional pinning)"""
data_size = self._estimate_size(data)
with self.ram_lock:
# Check if we need to evict
if not pin and partition_id not in self.ram_state:
evictions = self.eviction_policy.should_evict(data_size)
for evict_id in evictions:
self._evict_from_ram(evict_id)
# Add/update in RAM
old_data = self.ram_state.get(partition_id)
old_size = self._estimate_size(old_data) if old_data else 0
self.ram_state[partition_id] = data
self.ram_state.move_to_end(partition_id)
# Update metadata
if partition_id not in self.ram_metadata:
self.ram_metadata[partition_id] = PartitionMetadata(
partition_id=partition_id,
size_bytes=data_size,
last_access=time.time()
)
else:
self.ram_metadata[partition_id].size_bytes = data_size
self.ram_metadata[partition_id].last_modified = time.time()
self.ram_metadata[partition_id].is_dirty = True
self.ram_metadata[partition_id].is_pinned = pin
self.ram_metadata[partition_id].access_count += 1
# Update usage
with self.metrics_lock:
self.metrics['ram_usage'] += (data_size - old_size)
# Record to WAL if enabled
if self.wal_enabled:
self._record_to_wal(partition_id, data, 'PUT')
# Update eviction policy
self.eviction_policy.record_access(partition_id, data_size)
self.eviction_policy.current_usage = self.metrics['ram_usage']
def delete_partition(self, partition_id: str):
"""Delete partition from all tiers"""
with self.ram_lock:
if partition_id in self.ram_state:
size = self.ram_metadata.get(partition_id, PartitionMetadata(
partition_id, 0)).size_bytes
del self.ram_state[partition_id]
self.ram_metadata.pop(partition_id, None)
with self.metrics_lock:
self.metrics['ram_usage'] -= size
with self.ssd_lock:
if partition_id in self.ssd_index:
self._delete_from_ssd(partition_id)
del self.ssd_index[partition_id]
with self.metrics_lock:
self.metrics['ssd_usage'] -= self.ssd_index[partition_id].size_bytes
if self.wal_enabled:
self._record_to_wal(partition_id, None, 'DELETE')
def _add_to_ram(self, partition_id: str, data: Any, dirty: bool = False):
"""Internal: add to RAM"""
data_size = self._estimate_size(data)
self.ram_state[partition_id] = data
self.ram_state.move_to_end(partition_id)
if partition_id not in self.ram_metadata:
self.ram_metadata[partition_id] = PartitionMetadata(
partition_id=partition_id,
size_bytes=data_size,
last_access=time.time()
)
self.ram_metadata[partition_id].is_dirty = dirty
self.ram_metadata[partition_id].last_modified = time.time()
with self.metrics_lock:
self.metrics['ram_usage'] += data_size
def _evict_from_ram(self, partition_id: str):
"""Evict partition from RAM to SSD"""
if partition_id not in self.ram_state:
return
data = self.ram_state[partition_id]
metadata = self.ram_metadata[partition_id]
# Write to SSD if dirty
if metadata.is_dirty:
self._write_to_ssd(partition_id, data)
metadata.is_dirty = False
# Remove from RAM
del self.ram_state[partition_id]
with self.metrics_lock:
self.metrics['ram_usage'] -= metadata.size_bytes
self.metrics['evictions'] += 1
logger.debug(f"Evicted partition {partition_id} to SSD")
def _write_to_ssd(self, partition_id: str, data: Any):
"""Write partition to SSD"""
with self.ssd_lock:
filepath = self.ssd_path / f"{partition_id}.dat"
try:
with open(filepath, 'wb') as f:
pickle.dump(data, f)
# Update SSD index
if partition_id not in self.ssd_index:
self.ssd_index[partition_id] = PartitionMetadata(
partition_id=partition_id,
size_bytes=os.path.getsize(filepath),
last_access=time.time()
)
else:
self.ssd_index[partition_id].size_bytes = os.path.getsize(filepath)
self.ssd_index[partition_id].last_modified = time.time()
with self.metrics_lock:
self.metrics['ssd_usage'] += self.ssd_index[partition_id].size_bytes
except Exception as e:
logger.error(f"Failed to write {partition_id} to SSD: {e}")
raise
def _load_from_ssd(self, partition_id: str) -> Any:
"""Load partition from SSD"""
filepath = self.ssd_path / f"{partition_id}.dat"
try:
with open(filepath, 'rb') as f:
data = pickle.load(f)
# Update access time
if partition_id in self.ssd_index:
self.ssd_index[partition_id].last_access = time.time()
self.ssd_index[partition_id].access_count += 1
return data
except FileNotFoundError:
logger.error(f"Partition {partition_id} not found on SSD")
raise
except Exception as e:
logger.error(f"Failed to load {partition_id} from SSD: {e}")
raise
def _delete_from_ssd(self, partition_id: str):
"""Delete partition from SSD"""
filepath = self.ssd_path / f"{partition_id}.dat"
try:
if filepath.exists():
filepath.unlink()
except Exception as e:
logger.error(f"Failed to delete {partition_id} from SSD: {e}")
def _record_to_wal(self, partition_id: str, data: Any, operation: str):
"""Record operation to Write-Ahead Log"""
wal_entry = {
'timestamp': time.time(),
'partition_id': partition_id,
'operation': operation,
'data_size': self._estimate_size(data) if data else 0,
'checksum': hashlib.md5(pickle.dumps(data)).hexdigest() if data else None
}
self.wal.append(wal_entry)
with self.metrics_lock:
self.metrics['wal_size'] = len(self.wal)
def _flush_wal(self):
"""Flush WAL to durable storage"""
if not self.wal:
return
wal_file = self.checkpoint_path / f"wal_{int(time.time())}.log"
try:
with open(wal_file, 'a') as f:
for entry in self.wal:
f.write(json.dumps(entry) + '\n')
self.wal.clear()
with self.metrics_lock:
self.metrics['wal_size'] = 0
logger.info(f"Flushed {len(self.wal)} WAL entries")
except Exception as e:
logger.error(f"WAL flush failed: {e}")
def create_checkpoint(self, checkpoint_id: Optional[str] = None) -> str:
"""Create a consistent checkpoint"""
checkpoint_id = checkpoint_id or f"checkpoint_{int(time.time())}"
checkpoint_dir = self.checkpoint_path / checkpoint_id
checkpoint_dir.mkdir(exist_ok=True)
with self.checkpoint_lock:
try:
# 1. Flush all dirty RAM partitions to SSD
dirty_partitions = [
pid for pid, meta in self.ram_metadata.items()
if meta.is_dirty
]
for pid in dirty_partitions:
if pid in self.ram_state:
self._write_to_ssd(pid, self.ram_state[pid])
# 2. Copy all SSD partitions to checkpoint
partition_metadata = {}
total_size = 0
for partition_id in set(self.ssd_index.keys()) | set(self.ram_state.keys()):
# Get the latest version (from RAM if exists, else SSD)
if partition_id in self.ram_state:
data = self.ram_state[partition_id]
source = 'ram'
elif partition_id in self.ssd_index:
data = self._load_from_ssd(partition_id)
source = 'ssd'
else:
continue
# Save to checkpoint
checkpoint_file = checkpoint_dir / f"{partition_id}.dat"
with open(checkpoint_file, 'wb') as f:
pickle.dump(data, f)
size = os.path.getsize(checkpoint_file)
total_size += size
partition_metadata[partition_id] = {
'size': size,
'source': source,
'last_modified': time.time()
}
# 3. Save metadata
metadata = CheckpointMetadata(
checkpoint_id=checkpoint_id,
timestamp=time.time(),
partitions=set(partition_metadata.keys()),
size_bytes=total_size,
path=str(checkpoint_dir),
is_complete=True
)
with open(checkpoint_dir / 'metadata.json', 'w') as f:
json.dump({
'checkpoint_id': metadata.checkpoint_id,
'timestamp': metadata.timestamp,
'partitions': list(metadata.partitions),
'size_bytes': metadata.size_bytes,
'partitions_meta': partition_metadata
}, f, indent=2)
# 4. Flush WAL for durability
self._flush_wal()
with self.metrics_lock:
self.metrics['checkpoints'] += 1
logger.info(f"Created checkpoint {checkpoint_id} with {len(metadata.partitions)} partitions")
return checkpoint_id
except Exception as e:
logger.error(f"Checkpoint failed: {e}")
if checkpoint_dir.exists():
shutil.rmtree(checkpoint_dir)
raise
def restore_from_checkpoint(self, checkpoint_id: str):
"""Restore state from checkpoint"""
checkpoint_dir = self.checkpoint_path / checkpoint_id
if not checkpoint_dir.exists():
raise FileNotFoundError(f"Checkpoint {checkpoint_id} not found")
# Load metadata
with open(checkpoint_dir / 'metadata.json', 'r') as f:
metadata = json.load(f)
with self.checkpoint_lock:
# Clear current state
self.ram_state.clear()
self.ram_metadata.clear()
self.ssd_index.clear()
# Load all partitions
for partition_id in metadata['partitions']:
checkpoint_file = checkpoint_dir / f"{partition_id}.dat"
if checkpoint_file.exists():
with open(checkpoint_file, 'rb') as f:
data = pickle.load(f)
# Load to SSD (not RAM) initially
self._write_to_ssd(partition_id, data)
logger.info(f"Restored from checkpoint {checkpoint_id}")
def get_metrics(self) -> Dict[str, Any]:
"""Get current metrics"""
with self.metrics_lock:
metrics = self.metrics.copy()
# Add current state stats
with self.ram_lock, self.ssd_lock:
metrics.update({
'ram_partitions': len(self.ram_state),
'ssd_partitions': len(self.ssd_index),
'pinned_partitions': sum(1 for m in self.ram_metadata.values() if m.is_pinned),
'dirty_partitions': sum(1 for m in self.ram_metadata.values() if m.is_dirty),
'avg_partition_size_ram': (
sum(m.size_bytes for m in self.ram_metadata.values()) /
max(1, len(self.ram_metadata))
),
'avg_partition_size_ssd': (
sum(m.size_bytes for m in self.ssd_index.values()) /
max(1, len(self.ssd_index))
)
})
return metrics
def _estimate_size(self, obj: Any) -> int:
"""Estimate memory size of object"""
try:
return len(pickle.dumps(obj))
except:
return 0
def _checkpoint_worker(self):
"""Background checkpoint worker"""
while self.running:
try:
time.sleep(self.checkpoint_interval)
if self.running:
self.create_checkpoint()
except Exception as e:
logger.error(f"Checkpoint worker error: {e}")
def _wal_flush_worker(self):
"""Background WAL flush worker"""
while self.running:
try:
time.sleep(self.wal_flush_interval)
if self.running and len(self.wal) > 100: # Flush if WAL is large
self._flush_wal()
except Exception as e:
logger.error(f"WAL flush worker error: {e}")
def _alert_worker(self):
"""Background alert monitoring"""
alert_thresholds = {
'eviction_rate': 100, # evictions per minute
'ssd_hit_ratio': 0.3, # SSD hits should be <30% of total
'ram_usage_ratio': 0.9, # RAM usage >90%
'wal_size': 10000, # WAL entries
'checkpoint_duration': 300, # seconds
}
last_metrics = None
while self.running:
try:
time.sleep(60) # Check every minute
current_metrics = self.get_metrics()
if last_metrics:
# Calculate rates
eviction_rate = (
current_metrics['evictions'] - last_metrics['evictions']
) / 60.0
total_hits = current_metrics['ram_hits'] + current_metrics['ssd_hits']
ssd_hit_ratio = (
current_metrics['ssd_hits'] / total_hits
if total_hits > 0 else 0
)
ram_usage_ratio = current_metrics['ram_usage'] / self.ram_capacity
# Check thresholds
alerts = []
if eviction_rate > alert_thresholds['eviction_rate']:
alerts.append(f"High eviction rate: {eviction_rate:.1f}/sec")
if ssd_hit_ratio > alert_thresholds['ssd_hit_ratio']:
alerts.append(f"High SSD hit ratio: {ssd_hit_ratio:.1%}")
if ram_usage_ratio > alert_thresholds['ram_usage_ratio']:
alerts.append(f"High RAM usage: {ram_usage_ratio:.1%}")
if current_metrics['wal_size'] > alert_thresholds['wal_size']:
alerts.append(f"Large WAL: {current_metrics['wal_size']} entries")
if alerts:
logger.warning(f"ALERTS: {'; '.join(alerts)}")
# Here you would send to monitoring system
self._send_alerts(alerts)
last_metrics = current_metrics
except Exception as e:
logger.error(f"Alert worker error: {e}")
def _send_alerts(self, alerts: List[str]):
"""Send alerts to monitoring system (placeholder)"""
# Implement integration with Prometheus, CloudWatch, etc.
for alert in alerts:
logger.info(f"ALERT: {alert}")
# Example: requests.post(alerting_webhook, json={'message': alert})
class StreamingJoinPlanner:
"""Main streaming join planner with state tiering"""
def __init__(
self,
ram_capacity_gb: float = 10.0,
state_dir: str = "/var/lib/streaming",
max_checkpoint_retention: int = 10
):
ram_capacity = int(ram_capacity_gb * 1024 * 1024 * 1024)
self.state_manager = TieredStateManager(
ram_capacity_bytes=ram_capacity,
ssd_path=os.path.join(state_dir, "state"),
checkpoint_path=os.path.join(state_dir, "checkpoints")
)
self.max_checkpoint_retention = max_checkpoint_retention
self.join_configs: Dict[str, Dict] = {}
self.running = False
def start(self):
"""Start the planner"""
self.state_manager.start()
self.running = True
logger.info("StreamingJoinPlanner started")
def stop(self):
"""Stop the planner"""
self.running = False
self.state_manager.stop()
logger.info("StreamingJoinPlanner stopped")
def register_join(
self,
join_id: str,
left_key: str,
right_key: str,
window_size: timedelta,
hash_partitions: int = 100
):
"""Register a streaming join"""
self.join_configs[join_id] = {
'left_key': left_key,
'right_key': right_key,
'window_size': window_size,
'hash_partitions': hash_partitions,
'partitions': {}
}
logger.info(f"Registered join {join_id}")
def _hash_partition(self, key: str, num_partitions: int) -> int:
"""Hash partition function"""
return int(hashlib.md5(key.encode()).hexdigest(), 16) % num_partitions
def process_event(
self,
join_id: str,
event: Dict[str, Any],
is_left: bool
) -> List[Dict[str, Any]]:
"""Process an event and produce join results"""
if join_id not in self.join_configs:
raise ValueError(f"Join {join_id} not registered")
config = self.join_configs[join_id]
key_field = config['left_key'] if is_left else config['right_key']
key = str(event.get(key_field, ''))
if not key:
return []
# Partition key
partition_id = f"{join_id}_{'left' if is_left else 'right'}_{self._hash_partition(key, config['hash_partitions'])}"
# Get current state for this partition
state = self.state_manager.get_partition(partition_id) or {
'left_events': [],
'right_events': [],
'timestamps': []
}
# Add event
side = 'left_events' if is_left else 'right_events'
state[side].append(event)
state['timestamps'].append(time.time())
# Clean old events based on window
window_cutoff = time.time() - config['window_size'].total_seconds()
state['timestamps'] = [t for t in state['timestamps'] if t >= window_cutoff]
# Rebuild events list based on timestamps
cutoff_idx = 0
for i, ts in enumerate(state['timestamps']):
if ts >= window_cutoff:
cutoff_idx = i
break
state['left_events'] = state['left_events'][-len(state['timestamps']):]
state['right_events'] = state['right_events'][-len(state['timestamps']):]
# Try to produce joins
results = []
if is_left and state['right_events']:
for left_event in state['left_events']:
for right_event in state['right_events']:
results.append({**left_event, **right_event})
elif not is_left and state['left_events']:
for right_event in state['right_events']:
for left_event in state['left_events']:
results.append({**left_event, **right_event})
# Update state (mark dirty)
self.state_manager.put_partition(partition_id, state)
return results
def get_join_statistics(self, join_id: str) -> Dict[str, Any]:
"""Get statistics for a specific join"""
if join_id not in self.join_configs:
raise ValueError(f"Join {join_id} not registered")
metrics = self.state_manager.get_metrics()
config = self.join_configs[join_id]
return {
'join_id': join_id,
'config': config,
'state_metrics': metrics,
'partitions': len(self._get_join_partitions(join_id))
}
def _get_join_partitions(self, join_id: str) -> List[str]:
"""Get all partition IDs for a join"""
partitions = []
for partition_id in self.state_manager.ssd_index.keys():
if partition_id.startswith(f"{join_id}_"):
partitions.append(partition_id)
for partition_id in self.state_manager.ram_state.keys():
if partition_id.startswith(f"{join_id}_"):
if partition_id not in partitions:
partitions.append(partition_id)
return partitions
def force_checkpoint(self) -> str:
"""Force immediate checkpoint"""
return self.state_manager.create_checkpoint()
def cleanup_old_checkpoints(self):
"""Remove old checkpoints beyond retention limit"""
checkpoints = sorted(
self.state_manager.checkpoint_path.glob("checkpoint_*"),
key=lambda p: p.stat().st_mtime
)
if len(checkpoints) > self.max_checkpoint_retention:
to_delete = checkpoints[:-self.max_checkpoint_retention]
for cp in to_delete:
shutil.rmtree(cp)
logger.info(f"Deleted old checkpoint: {cp.name}")
# Example usage
if __name__ == "__main__":
# Initialize planner
planner = StreamingJoinPlanner(
ram_capacity_gb=2.0,
state_dir="/tmp/streaming_state"
)
# Register a join
planner.register_join(
join_id="user_click_join",
left_key="user_id",
right_key="user_id",
window_size=timedelta(minutes=15),
hash_partitions=50
)
# Start processing
planner.start()
try:
# Simulate events
for i in range(1000):
event = {'user_id': f'user_{i % 100}', 'value': i}
results = planner.process_event(
"user_click_join",
event,
is_left=(i % 2 == 0)
)
if i % 100 == 0:
print(f"Processed {i} events, results: {len(results)}")
print(f"Metrics: {planner.state_manager.get_metrics()}")
# Force checkpoint
checkpoint_id = planner.force_checkpoint()
print(f"Checkpoint created: {checkpoint_id}")
# Get statistics
stats = planner.get_join_statistics("user_click_join")
print(f"Join statistics: {stats}")
finally:
planner.stop()
planner.cleanup_old_checkpoints()
2. Test Suite
# test_tiered_state_manager.py
import os
import tempfile
import shutil
import pytest
import time
from tiered_state_manager import TieredStateManager, StreamingJoinPlanner
class TestTieredStateManager:
"""Test suite for TieredStateManager"""
@pytest.fixture
def temp_dir(self):
"""Create temporary directory for tests"""
tmpdir = tempfile.mkdtemp()
yield tmpdir
shutil.rmtree(tmpdir)
@pytest.fixture
def state_manager(self, temp_dir):
"""Create state manager instance"""
return TieredStateManager(
ram_capacity_bytes=1024 * 1024, # 1MB
ssd_path=os.path.join(temp_dir, "ssd"),
checkpoint_path=os.path.join(temp_dir, "checkpoints"),
wal_enabled=True
)
def test_basic_put_get(self, state_manager):
"""Test basic put and get operations"""
state_manager.put_partition("p1", {"data": "test"})
result = state_manager.get_partition("p1")
assert result == {"data": "test"}
def test_ram_eviction(self, state_manager):
"""Test RAM eviction when capacity exceeded"""
# Fill RAM beyond capacity (1MB)
large_data = "x" * (600 * 1024) # 600KB each
state_manager.put_partition("p1", large_data)
state_manager.put_partition("p2", large_data)
state_manager.put_partition("p3", large_data)
# Should have evicted at least one
metrics = state_manager.get_metrics()
assert metrics['evictions'] > 0
assert metrics['ram_partitions'] <= 2 # 1MB / 600KB ≈ 1.66
def test_ssd_fallback(self, state_manager):
"""Test loading from SSD when not in RAM"""
# Put large data to force eviction to SSD
large_data = "x" * (2 * 1024 * 1024) # 2MB
state_manager.put_partition("p1", large_data)
# Manually evict from RAM
state_manager._evict_from_ram("p1")
# Should load from SSD
result = state_manager.get_partition("p1")
assert result == large_data
metrics = state_manager.get_metrics()
assert metrics['ssd_hits'] > 0
def test_checkpoint_restore(self, state_manager):
"""Test checkpoint creation and restore"""
# Add some data
state_manager.put_partition("p1", {"value": 1})
state_manager.put_partition("p2", {"value": 2})
# Create checkpoint
checkpoint_id = state_manager.create_checkpoint()
# Verify checkpoint exists
checkpoint_dir = state_manager.checkpoint_path / checkpoint_id
assert checkpoint_dir.exists()
assert (checkpoint_dir / "metadata.json").exists()
# Create new state manager and restore
new_manager = TieredStateManager(
ram_capacity_bytes=1024 * 1024,
ssd_path=os.path.join(os.path.dirname(state_manager.ssd_path), "ssd_new"),
checkpoint_path=os.path.join(os.path.dirname(state_manager.checkpoint_path), "checkpoints_new")
)
new_manager.restore_from_checkpoint(checkpoint_id)
# Verify data
assert new_manager.get_partition("p1") == {"value": 1}
assert new_manager.get_partition("p2") == {"value": 2}
def test_wal_functionality(self, state_manager):
"""Test Write-Ahead Log"""
initial_wal_size = len(state_manager.wal)
state_manager.put_partition("p1", {"data": "test"})
state_manager.delete_partition("p1")
assert len(state_manager.wal) > initial_wal_size
# Flush WAL
state_manager._flush_wal()
assert len(state_manager.wal) == 0
def test_pinned_partition(self, state_manager):
"""Test pinned partition prevents eviction"""
large_data = "x" * (600 * 1024)
state_manager.put_partition("p1", large_data, pin=True)
state_manager.put_partition("p2", large_data)
state_manager.put_partition("p3", large_data)
# p1 should still be in RAM (pinned)
assert "p1" in state_manager.ram_state
assert state_manager.ram_metadata["p1"].is_pinned
def test_concurrent_access(self, state_manager):
"""Test concurrent access safety"""
import threading
def worker(thread_id):
for i in range(100):
state_manager.put_partition(f"p{thread_id}_{i}", {"thread": thread_id, "count": i})
state_manager.get_partition(f"p{thread_id}_{i}")
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
for t in threads:
t.join()
# Should not have corrupted state
metrics = state_manager.get_metrics()
assert metrics['ram_partitions'] > 0
class TestStreamingJoinPlanner:
"""Test suite for StreamingJoinPlanner"""
@pytest.fixture
def temp_dir(self):
tmpdir = tempfile.mkdtemp()
yield tmpdir
shutil.rmtree(tmpdir)
@pytest.fixture
def planner(self, temp_dir):
planner = StreamingJoinPlanner(
ram_capacity_gb=0.5,
state_dir=temp_dir
)
planner.start()
yield planner
planner.stop()
def test_join_registration(self, planner):
"""Test join registration"""
planner.register_join(
"test_join",
"user_id",
"user_id",
timedelta(minutes=5),
hash_partitions=10
)
stats = planner.get_join_statistics("test_join")
assert stats['join_id'] == "test_join"
assert stats['config']['hash_partitions'] == 10
def test_streaming_join(self, planner):
"""Test streaming join operation"""
planner.register_join(
"click_join",
"user_id",
"user_id",
timedelta(minutes=10),
hash_partitions=5
)
# Process left events
for i in range(10):
event = {'user_id': f'user_{i}', 'click_time': time.time()}
planner.process_event("click_join", event, is_left=True)
# Process right events (same user_ids)
results = []
for i in range(10):
event = {'user_id': f'user_{i}', 'view_time': time.time()}
results.extend(planner.process_event("click_join", event, is_left=False))
# Should have joins for matching keys
assert len(results) > 0
for result in results:
assert 'user_id' in result
assert 'click_time' in result
assert 'view_time' in result
def test_windowed_join(self, planner):
"""Test window-based join expiration"""
planner.register_join(
"windowed_join",
"key",
"key",
timedelta(seconds=1), # 1 second window
hash_partitions=1
)
# Add left event
planner.process_event("windowed_join", {'key': 'test', 'value': 1}, is_left=True)
# Wait for window to expire
time.sleep(1.5)
# Add right event with same key
results = planner.process_event("windowed_join", {'key': 'test', 'value': 2}, is_left=False)
# Should NOT join because window expired
assert len(results) == 0
def test_checkpoint_integration(self, planner):
"""Test checkpoint with join state"""
planner.register_join("test_join", "k", "k", timedelta(minutes=1))
# Add some state
for i in range(50):
planner.process_event("test_join", {'k': f'key_{i%10}', 'v': i}, is_left=True)
# Create checkpoint
checkpoint_id = planner.force_checkpoint()
# Restart planner
planner.stop()
new_planner = StreamingJoinPlanner(state_dir=planner.state_manager.state_dir)
new_planner.start()
new_planner.restore_from_checkpoint(checkpoint_id)
# State should be restored
stats = new_planner.get_join_statistics("test_join")
assert stats['state_metrics']['ram_partitions'] > 0 or stats['state_metrics']['ssd_partitions'] > 0
new_planner.stop()
# Integration test
def test_full_integration():
"""Full integration test with failure simulation"""
with tempfile.TemporaryDirectory() as tmpdir:
planner = StreamingJoinPlanner(
ram_capacity_gb=0.5,
state_dir=tmpdir
)
planner.start()
try:
# Register join
planner.register_join(
"integration_test",
"user_id",
"user_id",
timedelta(minutes=5),
hash_partitions=10
)
# Process stream
event_count = 0
for i in range(1000):
# Alternate left/right events
is_left = (i % 2 == 0)
event = {'user_id': f'user_{i % 50}', 'event_id': i, 'ts': time.time()}
results = planner.process_event("integration_test", event, is_left=is_left)
event_count += 1
if i % 200 == 0:
print(f"Processed {i} events, RAM: {planner.state_manager.get_metrics()['ram_usage']/1024/1024:.1f}MB")
# Force checkpoint
cp_id = planner.force_checkpoint()
print(f"Checkpoint: {cp_id}")
# Verify metrics
metrics = planner.state_manager.get_metrics()
assert metrics['ram_hits'] > 0 or metrics['ssd_hits'] > 0
assert metrics['checkpoints'] >= 1
finally:
planner.stop()
3. Configuration & Deployment
# config/join_planner.yaml
planner:
ram_capacity_gb: 16
state_dir: /var/lib/streaming-join
max_checkpoint_retention: 20
checkpoint_interval_sec: 300
wal_flush_interval_sec: 60
eviction:
policy: "lru" # Options: lru, lfu, size_based
ram_high_watermark: 0.85 # Start evicting at 85% RAM usage
ram_low_watermark: 0.70 # Stop evicting at 70% RAM usage
min_partition_size_mb: 10 # Minimum partition size to consider for eviction
checkpoint:
compression: "snappy" # Options: none, gzip, snappy, lz4
sync_to_disk: true
max_concurrent: 2
monitoring:
metrics_port: 9090
alert_channels:
- type: "prometheus"
endpoint: "http://prometheus:9090"
- type: "slack"
webhook: "${SLACK_WEBHOOK}"
alerts:
eviction_rate:
threshold: 100 # per minute
cooldown: 300 # 5 minutes
ssd_hit_ratio:
threshold: 0.4 # 40%
cooldown: 300
checkpoint_duration:
threshold: 300 # seconds
cooldown: 600
joins:
- join_id: "user_activity"
left_key: "user_id"
right_key: "user_id"
window_size: "15m"
hash_partitions: 100
state_ttl: "24h" # Auto-cleanup after 24h
- join_id: "order payment"
left_key: "order_id"
right_key: "order_id"
window_size: "1h"
hash_partitions: 50
4. Docker Deployment
# Dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN useradd -m -u 1000 streaming && chown -R streaming:streaming /app
USER streaming
EXPOSE 9090
CMD ["python", "-m", "tiered_join_planner", "--config", "/config/join_planner.yaml"]
# docker-compose.yml
version: '3.8'
services:
join-planner:
build: .
ports:
- "9090:9090"
volumes:
- ./config:/config:ro
- ./data/state:/var/lib/streaming/state
- ./data/checkpoints:/var/lib/streaming/checkpoints
environment:
- LOG_LEVEL=INFO
- PROMETHEUS_MULTIPROC_DIR=/tmp
deploy:
resources:
limits:
memory: 20G
reservations:
memory: 4G
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9090/metrics"]
interval: 30s
timeout: 10s
retries: 3
5. Metrics & Monitoring
# metrics_exporter.py
from prometheus_client import Counter, Gauge, Histogram, start_http_server
# Define metrics
RAM_HITS = Counter('join_ram_hits_total', 'Total RAM hits')
SSD_HITS = Counter('join_ssd_hits_total', 'Total SSD hits')
EVICTIONS = Counter('join_evictions_total', 'Total evictions')
CHECKPOINTS = Counter('join_checkpoints_total', 'Total checkpoints')
CHECKPOINT_DURATION = Histogram('join_checkpoint_duration_seconds', 'Checkpoint duration')
RAM_USAGE = Gauge('join_ram_usage_bytes', 'Current RAM usage')
SSD_USAGE = Gauge('join_ssd_usage_bytes', 'Current SSD usage')
WAL_SIZE = Gauge('join_wal_size', 'WAL queue size')
PARTITION_COUNT = Gauge('join_partition_count', 'Number of partitions', ['tier'])
class MetricsCollector:
def __init__(self, state_manager: TieredStateManager):
self.state_manager = state_manager
start_http_server(9090)
def update_metrics(self):
"""Update all metrics"""
metrics = self.state_manager.get_metrics()
RAM_USAGE.set(metrics['ram_usage'])
SSD_USAGE.set(metrics['ssd_usage'])
WAL_SIZE.set(metrics['wal_size'])
PARTITION_COUNT.labels(tier='ram').set(metrics['ram_partitions'])
PARTITION_COUNT.labels(tier='ssd').set(metrics['ssd_partitions'])
6. Key Features Summary
State Tiering
- RAM Tier: LRU cache with configurable capacity
- SSD Tier: Write-back cache with persistence
- Automatic Migration: Based on access patterns and capacity pressure
Eviction Policy
- LRU with access frequency weighting
- Configurable watermarks (high/low)
- Pinned partitions for critical state
- Batch eviction to minimize I/O
Checkpointing
- Consistent snapshots (flush dirty state first)
- Incremental checkpoint support (optional)
- WAL for durability
- Configurable retention policy
Alerting
- Eviction Rate Alert: >100 evictions/min indicates undersized RAM
- SSD Hit Ratio Alert: >40% SSD hits indicates poor cache locality
- Checkpoint Duration Alert: >5min indicates I/O bottleneck
- WAL Size Alert: >10k entries indicates checkpoint issues
- RAM Usage Alert: >90% sustained usage
Fault Tolerance
- WAL for operation recovery
- Periodic checkpoints
- Atomic checkpoint creation
- Partition-level recovery
Monitoring
- Prometheus metrics endpoint
- Per-join statistics
- Tier utilization metrics
- Operation latency histograms
7. Performance Tuning Guidelines
-
RAM Sizing:
- Start with 10-20% of total state size
- Monitor
ssd_hit_ratio - should be <30% for good performance
-
Partition Sizing:
- Target 10-100MB per partition
- Too small → overhead; too large → poor load balancing
-
Checkpoint Tuning:
- Frequency: Balance recovery time vs overhead
- Compression: Use snappy for speed, gzip for size
- I/O: Place checkpoints on separate SSD from state
-
WAL Configuration:
- Flush frequently if checkpoint interval is long
- Consider async WAL for higher throughput
-
Alert Thresholds:
- Adjust based on SLA requirements
- Set reasonable cooldowns to avoid alert storms
This implementation provides a production-ready foundation for a streaming join planner with state tiering. The modular design allows for easy extension (different eviction policies, storage backends, etc.) and includes comprehensive monitoring and alerting capabilities essential for production deployments.