We are designing a stream processing DSL (Domain Specific Language) that includes temporal operators. The design should cover:
- Compiler pipeline: How the DSL code is transformed into an executable form.
- Runtime scheduling: How the system schedules the execution of operators, considering time and data dependencies.
- Backpressure handling: How the system deals with situations where the producer is faster than the consumer.
- Debuggability: Features to help users debug their stream processing applications.
We'll break down each part:
-
Compiler Pipeline:
- The DSL will have a set of temporal operators (e.g., window, slide, delay, throttle, etc.) and basic stream operations (map, filter, etc.).
- The compiler will parse the DSL code and build an abstract syntax tree (AST).
- The AST will be transformed into a logical plan (a directed acyclic graph, DAG) of operators.
- The logical plan will be optimized (e.g., operator fusion, predicate pushdown) and then converted into a physical plan that is specific to the runtime.
- The physical plan may be compiled to an executable form (e.g., Java bytecode, or a stream of bytecode for a custom VM) or interpreted.
-
Runtime Scheduling:
- The runtime will execute the physical plan as a set of connected operators.
- Each operator will have one or more input streams and one or more output streams.
- Scheduling can be done in a push-based manner (data-driven) or pull-based (demand-driven). We'll likely use push with backpressure.
- For temporal operators, time is a first-class concept. We may have:
- Event time: time based on the event itself (e.g., timestamp in the event).
- Processing time: time based on the machine's clock.
- The runtime must manage watermarks (for event time) to track progress and trigger window computations.
- Operators that require time (like windows) will be scheduled to emit results when the watermark passes the end of the window.
-
Backpressure Handling:
- We need a mechanism to prevent fast producers from overwhelming slow consumers.
- In a push-based system, when an operator's output buffer is full, it should signal upstream to slow down.
- We can implement a credit-based system or use bounded buffers with blocking.
- Alternatively, we can design the system to be reactive (like Reactive Streams) where demand is pulled from downstream.
-
Debuggability:
- We need to provide tools to inspect the stream processing application at runtime.
- Features may include:
- Logging at different levels (per operator, per stream).
- Metrics collection (throughput, latency, buffer sizes, etc.).
- Ability to dump the state of operators (for stateful operators).
- Tracing: trace individual events through the system (like distributed tracing).
- A UI or CLI to monitor and debug.
Let's design a simple example DSL and then outline the compiler and runtime.
Example DSL:
stream = Input.from("topic1")
stream
.map(event -> event.value * 2)
.window(TumblingEventTimeWindows.of(Size.ofMinutes(5)))
.reduce((a, b) -> a + b)
.filter(sum -> sum > 100)
.sink(Output.to("topic2"))
Steps in the compiler:
- Parse: The DSL code is parsed and converted to an AST.
- Logical Plan: The AST is converted to a logical DAG. Each node is an operator (Source, Map, Window, Reduce, Filter, Sink).
- Optimization:
- Fuse adjacent stateless operators (e.g., Map and Filter) into a single operator to reduce data movement.
- Push down filters (if possible) to reduce data volume early.
- For window operations, we might split the window operator into two: one for assigning events to windows and another for emitting results.
- Physical Plan: The logical plan is converted to a physical plan. This includes:
- Choosing the implementation of each operator (e.g., a hash-based reduce vs. sort-based).
- Deciding on the parallelism (number of instances for each operator).
- Deciding on the data distribution (e.g., keyBy for window operations).
- Code Generation: The physical plan is compiled to an executable form. We can generate code for each operator that processes a record and then chain them together.
Runtime:
- The runtime will have a set of tasks (operator instances) that are scheduled on threads (or distributed across machines).
- Each operator has input and output buffers (queues). The buffers are bounded to apply backpressure.
- The scheduler will run operators in a thread pool. Each operator instance runs in its own thread (or multiple operators share a thread if they are fused).
- For time-based operators, we have a timer service that manages watermarks and triggers window emissions.
Backpressure:
- We can use a bounded queue for each output buffer. When the buffer is full, the operator blocks on put (or uses a non-blocking approach with a fallback).
- Alternatively, we can implement a request-n mechanism: an operator only requests a certain number of records from its upstream when it has capacity. This is similar to Reactive Streams.
Debuggability:
- We can have a debugging mode that records every event that passes through an operator (or samples) and allows replay.
- We can also have a way to plug in custom inspectors that can examine the state of an operator at runtime.
Let's outline the design in more detail:
Compiler Pipeline:
- Frontend: Parses the DSL and builds an AST. We can use an existing parser generator (like ANTLR) or hand-write a parser for a simple DSL.
- Logical Plan Builder: Traverses the AST and builds a logical DAG. Each node has:
- Operator type (source, map, window, etc.)
- Configuration (e.g., window size, key selector for window, etc.)
- Input and output edges.
- Logical Optimizer: Applies rules to the logical plan:
- Rule 1: Fuse adjacent stateless operators (no state, no time dependency) into a single operator.
- Rule 2: Push down filters (if the filter condition can be evaluated before a window, then push it before the window).
- Rule 3: For window operations that require keying, we might insert a keyBy operator (if not already present) and then partition the window operator by key.
- Physical Plan Builder: Converts the logical plan to a physical plan. This includes:
- Assigning parallelism to each operator.
- For distributed execution, we need to decide how to partition the data (e.g., hash partition by key).
- Choosing implementations (e.g., for reduce, we might use a combinable reduce if possible).
- Code Generator: Generates code for each operator. We can generate Java code and compile it at runtime, or generate bytecode directly. Alternatively, we can have a generic operator interpreter and just describe the operator in the physical plan (but this would be slower).
Alternatively, we can skip code generation and have a set of generic operator implementations (like a MapOperator, WindowOperator, etc.) and the physical plan just configures them.
Given the complexity of temporal operators (which require state and time management), we might have:
WindowOperator: This operator maintains state for each window (or for each key and window). It also has a timer service to trigger when the watermark passes the window end.
So, we can have a set of built-in operators and the physical plan is a DAG of these built-in operators with configuration.
Therefore, the code generation step might not generate new code but rather instantiate and connect the built-in operators with the given configuration.
However, for user-defined functions (like the map and reduce functions), we need to compile those. We can use the Java compiler (if the DSL is in Java) or we can generate a class that implements a Function interface.
So, the compiler pipeline:
DSL Code -> Parser -> AST -> Logical Plan -> Optimized Logical Plan -> Physical Plan -> (Optional) Code Gen for UDFs -> Serialized Physical Plan
The serialized physical plan (a set of operator descriptors with configuration and serialized UDFs) is sent to the runtime.
Runtime:
The runtime has:
- ClusterManager: Manages the distribution of tasks (operator instances) across worker nodes.
- Worker: A JVM (or other process) that runs a set of operator instances.
- OperatorInstance: An instance of an operator (with a specific parallelism index). Each operator instance has:
* Input buffers (from upstream operator instances)
* Output buffers (to downstream operator instances)
* State (if stateful)
* A thread (or uses a shared thread pool) to process records.
Execution model:
- Each operator instance runs in a loop: take a record from the input buffer, process it (apply the operator logic), and put the result in the output buffer.
- For backpressure: if the output buffer of an operator is full, then the operator will block when trying to put, which will eventually cause the upstream operator to block (if it's also pushing). Alternatively, we can have the operator only take from input when it has capacity downstream (pull-based). We'll choose push with bounded buffers and blocking.
- For time: we have a central timer service (or each operator has its own timer) that fires when watermarks advance. The timer service will notify the window operator, which then emits the window contents.
Backpressure:
- We use bounded queues for each channel (output buffer). The size is configurable.
- When an operator tries to put a record into a full buffer, it blocks (or uses offer with timeout and then retries). This will cause the operator to slow down.
However, if we have multiple upstream operators, blocking on one output buffer might not stop the operator from processing more from other inputs. We need a mechanism to apply backpressure to the specific upstream.
We can have:
Each operator instance has a set of upstream channels. When processing a record from a channel, we try to put to all downstream channels. If one of them is full, we put the record back (or keep it) and then backpressure that channel (by not pulling more from that upstream until the downstream has space).
Alternatively, we can have a credit-based system:
Each downstream operator sends credits (how many records it can accept) to its upstream. The upstream can only send that many records.
Given the complexity, we might start with a simple blocking queue and then evolve.
Debuggability:
- We can have a debug server that accepts commands (e.g., dump state of operator, enable/disable logging, etc.)
- We can also have a trace mode that records the path of each event (or a sample) through the system, with timestamps.
We can design:
Each operator can be wrapped with a debugging wrapper that logs:
- When a record arrives (with a trace ID if available)
- What the record contains (maybe sample)
- When the record is emitted.
We can also snapshot the state of stateful operators (like windows) on demand.
We can have a UI that shows the DAG and allows clicking on an operator to see its state and metrics.
Given the complexity, we might not implement all at once.
Summary:
We design a stream processing DSL with temporal operators. The compiler pipeline transforms the DSL code into a physical plan of built-in operators. The runtime executes the physical plan with backpressure using bounded buffers. Debuggability is provided by logging, metrics, and state inspection.
Let's write a high-level design document with these components.
However, note: the question asks for a design, so we need to provide an outline of the system.
We can structure the answer as:
- Introduction: What the DSL is and the key features.
- Compiler Pipeline: Steps from DSL code to executable.
- Runtime: How the physical plan is executed, including scheduling and backpressure.
- Debuggability: Features and how they are implemented.
- Example: A simple example of the DSL and how it is compiled and run.
Let's write accordingly.
I'll design a comprehensive stream processing DSL with temporal operators, addressing all requested aspects. Let's call this Tempest Streams.
1. Language Design & DSL Syntax
Core Temporal Operators
stream {
// Temporal windows
window(Tumbling.of(5.minutes)) {
aggregate(sum(key))
}
// Session windows with inactivity gap
session(30.seconds, timeout = 10.seconds) {
count()
}
// Sliding windows
sliding(1.minute, 30.seconds) {
avg(temperature)
}
// Temporal joins
streamA
.join(streamB,
within(10.seconds),
on = (a, b) -> a.id == b.id)
.select { a, b -> a.data + b.data }
// Rate limiting with temporal control
throttle(100.per.second)
// Delay/backfill
delay(5.seconds)
// Time-based filtering
during(businessHours(9, 17))
// Watermark management
withWatermark("eventTime", 30.seconds)
// Temporal patterns (complex event processing)
pattern {
"hot" -> temperature > 80
within(5.minutes)
followedBy("cool") -> temperature < 60
}
}
2. Compiler Pipeline
Multi-Stage Compilation
DSL Source → AST → Logical Plan → Physical Plan → Executable
Stage 1: Parsing & AST Construction
- Custom parser (ANTLR/Parboiled) with temporal grammar
- AST nodes:
StreamNode, WindowNode, TemporalJoinNode, WatermarkNode
- Type checking with temporal type system (event time vs processing time)
Stage 2: Logical Optimization
// Rules:
1. Window fusion: adjacent windows on same key → single window
2. Watermark propagation: push watermark constraints upstream
3. Time-based predicate pushdown: filter before window when possible
4. Temporal join reordering: smaller time-bound stream first
Stage 3: Physical Planning
PhysicalOperator = (
source: KafkaSource(topic, timestampExtractor),
node: WindowOperator(
type= TUMBLING,
size= 300s,
trigger= WatermarkTrigger(lateness=30s),
state= RocksDBStateBackend,
shuffle= HashPartitioning(key_selector)
),
next: SinkOperator(ElasticsearchSink)
)
Stage 4: Code Generation
- Option A: Generate Java/Scala code (compile to JVM bytecode)
- Option B: Generate executable specifications for runtime interpreter
- Option C: Compile to Flink/Spark native plan (for compatibility)
3. Runtime Scheduling & Execution
Hierarchical Scheduler
Master Scheduler (cluster level)
├── Job Scheduler (per topology)
│ ├── Operator Graph Scheduler
│ │ ├── Time Wheel (for timers/watermarks)
│ │ ├── Watermark Coordinator
│ │ └── Resource Allocator
│ └── Backpressure Controller
└── State Manager
Temporal Execution Model
class TemporalOperator {
// Dual time contexts
EventTimeContext eventTime;
ProcessingTimeContext processingTime;
// Time-aware processing
void process(Record record) {
// 1. Extract/assign event time
timestamp = extractor.extract(record);
// 2. Update watermark if needed
watermark = max(watermark, timestamp - allowedLateness);
// 3. Assign to temporal buckets (windows/sessions)
Window window = assigner.assign(timestamp);
// 4. Buffer/aggregate
state.put(window, aggregate(record));
// 5. Check triggers
if (trigger.shouldEmit(watermark, window, processingTime.now())) {
emit(state.get(window));
}
}
}
Watermark Propagation Algorithm
def propagate_watermark(upstream_watermarks):
# Parallel stream: take min
# Branching stream: take min of branches
# After shuffle: preserve per-key ordering
return min(upstream_watermarks) - out_of_order_bound
4. Backpressure Handling
Multi-Level Backpressure Strategy
Level 1: Queue-Based
class BoundedChannel<T>(capacity: Int) {
private val queue = ArrayBlockingQueue<T>(capacity)
fun trySend(record: T): Boolean {
return queue.offer(record, 100, TimeUnit.MILLISECONDS)
}
fun poll(timeout: Long): T? {
return queue.poll(timeout, TimeUnit.MILLISECONDS)
}
}
Level 2: Credit-Based (Reactive Streams inspired)
trait Subscriber {
def request(n: Long): Unit // Request n more elements
}
trait Publisher {
def subscribe(sub: Subscriber): Unit
}
// Backpressure propagates upstream through demand signals
Level 3: Adaptive Rate Limiting
class AdaptiveThrottler:
def __init__(self):
self.throughput_history = deque(maxlen=100)
self.latency_history = deque(maxlen=100)
def should_throttle(self, downstream_latency):
# If downstream latency > threshold, reduce rate
if downstream_latency > LATENCY_P95_THRESHOLD:
self.current_rate *= 0.9
elif downstream_latency < LATENCY_P5_THRESHOLD:
self.current_rate *= 1.1
Level 4: Priority-Based Dropping
- Watermarked data (not late) → high priority
- Late data (within allowed lateness) → medium priority
- Out-of-order data (beyond lateness) → low priority/drop
5. Debuggability System
A. Observability Stack
1. Distributed Tracing
class TraceContext {
UUID traceId;
Stack<Span> activeSpans; // Each operator creates a span
void recordOperatorMetrics(
String operatorId,
long inputCount,
long outputCount,
long processingTimeNanos,
WindowState snapshot
) {
// Send to tracing system (Jaeger/Zipkin)
}
}
2. State Introspection API
// Query operator state at runtime
debugger.inspectOperator("window-3") {
it.currentWindows().forEach { window ->
println("Window: $window, Count: ${it.count(window)}, " +
"Sum: ${it.sum(window)}, " +
"FirstEvent: ${it.firstEventTime(window)}, " +
"LastEvent: ${it.lastEventTime(window)}")
}
it.watermark().let { println("Current watermark: $it") }
}
3. Temporal Replay
class TemporalReplayer:
def replay_from_checkpoint(self, checkpoint_id, target_time):
# Reconstruct state at checkpoint
state = self.state_manager.load(checkpoint_id)
# Replay events from checkpoint to target_time
events = self.event_log.query(
from_time=checkpoint.timestamp,
to_time=target_time,
watermark=checkpoint.watermark
)
return self.execute_replay(state, events)
4. Time Travel Debugging
// Define breakpoints with temporal conditions
debugger.setBreakpoint(
operator = "temperature-window",
condition = "window.end == 2024-01-01T12:00:00Z && count > 1000",
action = CAPTURE_STATE + PAUSE
)
B. Visual Debugging UI
Topology View:
Watermark Timeline:
Event Time ──────────────────────────►
│ ┌───┐
Watermark │───────┘ └───────────────►
│ ↑ ↑
└───────┘ └─── Late events allowed (30s)
Window 1 Window 2
State Explorer:
- Click any window operator → see:
- All active windows with their start/end times
- Aggregated values per window
- Watermark progress
- Late event count
C. Logging & Metrics
Structured Logging (JSON):
{
"timestamp": "2024-01-01T12:00:00.000Z",
"traceId": "a1b2c3d4",
"operator": "sales-window",
"window": {"start": "2024-01-01T11:55:00Z", "end": "2024-01-01T12:00:00Z"},
"eventTime": "2024-01-01T11:58:30Z",
"processingTime": "2024-01-01T12:00:00.500Z",
"watermark": "2024-01-01T11:59:30Z",
"action": "EMIT",
"result": {"totalSales": 15000.50, "count": 42}
}
Key Metrics (Prometheus format):
# HELP tempest_window_late_events Total late events
# TYPE tempest_window_late_events counter
tempest_window_late_events{operator="window-1"} 15
# HELP tempest_watermark_lag Watermark lag (processing_time - watermark)
# TYPE tempest_watermark_lag gauge
tempest_watermark_lag{operator="window-1"} 2.5
# HELP tempest_window_state_size Size of window state (bytes)
# TYPE tempest_window_state_size gauge
tempest_window_state_size{operator="window-1",state="rocksdb"} 1048576
6. Fault Tolerance
Checkpointing with Temporal Consistency
class TemporalCheckpoint {
// Global checkpoint barrier
long checkpointId;
// Per-operator checkpoint
Map<String, OperatorState> operatorStates = {
"window-1": WindowState(
windows = {window1: agg1, window2: agg2},
watermark = 1672567200000, // Unix millis
timerService = {timers...}
)
};
// Consistent cut across all operators at specific logical time
Instant logicalTime; // Event time or processing time
}
Recovery Strategy
- Watermark Reset: On failure, reset watermark to checkpoint watermark
- State Restoration: Load operator state from checkpoint
- Replay: Replay events from checkpoint's last processed offset
- Time Correction: Adjust timers based on processing time elapsed
7. Example: Complete Pipeline
// User DSL
val pipeline = tempest {
fromKafka("iot-sensors",
timestampExtractor = EventTimeExtractor("timestamp"))
.withWatermark(maxOutOfOrder = 5.seconds)
// Remove outliers
.filter { it.value in 0..100 }
// 1-minute tumbling windows per sensor
.keyBy { it.sensorId }
.window(Tumbling.of(1.minute))
.aggregate(
initializer = SensorAgg(),
accumulator = { agg, event -> agg.add(event.value) },
combiner = SensorAgg::merge
)
// Join with calibration data (temporal join)
.join(calibrationStream,
within(30.seconds),
on = (s, c) -> s.sensorId == c.sensorId)
.select { sensor, calib ->
sensor.calibrate(calib.factor)
}
// Session windows for maintenance periods
.window(Session.withGap(10.minutes))
.process(SessionAnalyzer())
.toElasticsearch("sensor-metrics",
bulkSize = 1000,
flushInterval = 5.seconds)
}
// Compiler generates:
// 1. Logical DAG with 8 operators
// 2. Physical plan: 12 parallel instances (keyBy partitions)
// 3. State backend: RocksDB with incremental checkpoints
// 4. Watermark strategy: periodic (1s) with aligned checkpoints
// Runtime:
// - Master node coordinates 3 worker nodes
// - Each operator: 1-4 parallel instances
// - Bounded queues: 10,000 records each
// - Checkpoint every 30s to S3
// - Metrics pushed to Prometheus every 10s
// - Tracing enabled for DEBUG log level
8. Advanced Features
Temporal SQL Extension
SELECT sensorId,
TUMBLE(eventTime, INTERVAL '1' MINUTE) as window,
AVG(value) as avgTemp,
COUNT(*) as count
FROM iot_stream
WHERE eventTime BETWEEN TIMESTAMP '2024-01-01' AND TIMESTAMP '2024-01-02'
GROUP BY sensorId, TUMBLE(eventTime, INTERVAL '1' MINUTE)
HAVING COUNT(*) > 100
Dynamic Window Adjustment
// Windows adjust based on data rate
stream.window(
DynamicTumbling.of(
baseSize = 1.minute,
maxSize = 15.minutes,
adjuster = { currentRate, windowCount ->
if (currentRate > 10000) 30.seconds
else if (windowCount > 1000) 2.minutes
else 1.minute
}
)
)
9. Implementation Priorities
Phase 1 (MVP):
- Basic window operators (tumbling/sliding)
- Simple backpressure (bounded queues)
- Checkpointing to local filesystem
- Basic metrics (throughput, latency)
Phase 2:
- Temporal joins
- Watermark propagation
- Distributed tracing
- State backend abstraction (RocksDB/Heaps)
Phase 3:
- Advanced debugger UI
- Dynamic scaling
- Exactly-once guarantees across sinks
- Time travel queries
Phase 4:
- Predictive autoscaling based on temporal patterns
- Anomaly detection on watermark lag
- SQL layer with temporal extensions
- Multi-datacenter active-active
This design provides:
- Expressive temporal DSL with first-class time semantics
- Sophisticated runtime with hierarchical scheduling
- Multi-level backpressure preventing overload
- Production-ready debugability with tracing, replay, and visualization
- Fault tolerance with temporally consistent checkpoints
The key innovation is treating time as a first-class citizen throughout the stack—from DSL syntax through compiler optimizations to runtime execution—enabling precise temporal reasoning while maintaining operational excellence.