We are going to design a reactive stream pipeline that includes:
- Backpressure handling: We'll use a bounded buffer or a strategy to handle backpressure.
- Materialized views: We'll have a way to collect the results into a materialized view (like a collection or a stream that can be consumed later).
- Testing: We'll write tests to verify the pipeline behavior, including backpressure.
We'll use Project Reactor (a popular reactive library for Java) for this example.
Steps:
a. Create a Flux (or Mono) that generates data at a fast rate (simulating a fast source).
b. Apply backpressure by using a bounded buffer or by using operators that allow controlling the rate.
c. Process the data (e.g., map, filter, etc.).
d. Materialize the results into a collection (or a sink) that we can inspect in tests.
However, note that in reactive streams, backpressure is a demand-driven mechanism. We can simulate backpressure by using a bounded buffer and then having a slow consumer.
Alternatively, we can use onBackpressureBuffer or onBackpressureDrop but note that these are ways to handle excess when the downstream can't keep up.
Let's design a pipeline that:
- Has a fast source (using
Flux.range with a high frequency).
- We'll then apply a slow processing (simulated by a delay) to create a backpressure scenario.
- We'll use a bounded buffer (with
onBackpressureBuffer having a max size) and then check what happens when the buffer overflows.
But note: onBackpressureBuffer with a max size will throw an exception when the buffer overflows and the downstream hasn't requested. However, we might want to test the behavior when we drop elements.
Alternatively, we can use onBackpressureDrop to drop when the buffer is full.
However, the requirement says "backpressure handling", so we might want to see how the pipeline behaves when the downstream is slow and we have a bounded buffer.
Let's do:
Source: Flux.range(1, 1000).delayElements(Duration.ofMillis(10)) // 1000 elements, 10ms apart -> 100 elements per second.
Then we have a slow processor: .delayElements(Duration.ofMillis(100)) // now each element takes 100ms -> 10 elements per second.
This will cause the source to produce 100 elements per second and the processor to consume 10 per second -> backpressure.
We can then apply a bounded buffer of size 50 and see that after 50 elements in the buffer, the source will be blocked until the buffer has space.
But note: the delayElements in the source and processor are asynchronous (by default, they use a default scheduler). We need to manage the schedulers to control the rate.
Alternatively, we can use a publishOn to change the execution context and then use a bounded buffer.
However, the reactive streams specification says that the source should not produce more than the demand from the downstream. But in our case, we are generating at a fixed rate regardless of demand? Actually, the delayElements operator will respect backpressure? Yes, because it's a reactive operator.
But we want to see the effect of a bounded buffer in between. So we can insert a onBackpressureBuffer with a max size and then see that when the buffer is full, the source will be paused (because the downstream (the buffer) will not request more until it has drained).
Alternatively, we can use a Flux that generates without respecting backpressure (like Flux.create with a unbounded queue) and then put a bounded buffer after.
Let's do:
Step 1: Create a source that generates without backpressure (using Flux.create and pushing elements without checking demand). This is not standard and might break the reactive streams contract, but for testing we can do it.
However, note that in Reactor, the Flux.create does respect backpressure by default? Actually, Flux.create uses a RingBuffer and by default it has a bounded buffer (with a size of 256) and will drop if overflow? Actually, the Flux.create has an overstrategy option. We can set it to Buffer and then set a buffer size? Actually, we can use Flux.<Integer>create(sink -> { ... }, FluxSink.OverflowStrategy.BUFFER) and then set the buffer size? The OverflowStrategy.BUFFER will use an unbounded queue? Actually, the Flux.create with BUFFER will use an unbounded queue and that is not safe.
We want to simulate a source that produces faster than the downstream and then we want to see the effect of a bounded buffer.
Alternatively, we can use Flux.range and then publishOn a fixed thread pool with a bounded queue? That's too low level.
Let me think: we want to have a source that produces at a fixed rate (say 1000 elements per second) and then a slow consumer (10 elements per second). The backpressure will cause the source to slow down if the operator chain respects backpressure.
Actually, the delayElements operator in the source and the slow processor are both respecting backpressure. So the source will only produce when the downstream requests. So we don't need an extra buffer? Then the backpressure will be handled by the source slowing down.
But the requirement is to have a backpressure handling in the pipeline (maybe by inserting a buffer). So let's insert a buffer that is bounded and then see that when the buffer is full, the source is blocked.
We can do:
source -> onBackpressureBuffer(50) -> slowProcessor
Now, the source will try to produce as fast as it can (but note: delayElements in the source is also respecting backpressure? Actually, the source Flux.range is a synchronous source and by default it will produce all elements at once and then the delayElements will schedule them with a delay. But the delayElements operator will request from upstream in batches? Actually, the delayElements operator uses a Scheduler and by default it requests Long.MAX_VALUE? That means it will request all at once and then schedule them. So the source will produce all at once and then the delayElements will schedule them. That doesn't respect backpressure from the downstream of delayElements.
So we need to make sure that the source respects backpressure. We can use Flux.range and then publishOn to a bounded scheduler? Or we can use Flux.generate and respect the demand.
Alternatively, let's change the source to use Flux.create with a bounded buffer and then we push elements without checking the demand? That would break the contract.
Actually, for testing backpressure, we can use the StepVerifier with thenRequest to control the demand.
But the requirement says "engineer a reactive stream pipeline with backpressure handling", meaning we design a pipeline that can handle backpressure (by having a buffer or by dropping) and then we test it.
Let's do:
We'll create a pipeline:
Flux<Integer> source = Flux.range(1, 1000)
.doOnNext(i -> log.info("Generated: {}", i))
.delayElements(Duration.ofMillis(10)); // generates 100 per second
Then we have a slow processor:
.delayElements(Duration.ofMillis(100)) // processes 10 per second
Now, we insert a bounded buffer of 50 between the source and the slow processor? Actually, the `delayElements` in the source will produce 100 per second and the slow processor consumes 10 per second. The `delayElements` operator in the source will buffer the elements in its own queue? Actually, the `delayElements` operator uses a `Scheduler` and by default it uses a `parallel` scheduler which has an unbounded queue? That's not what we want.
We want to have a bounded buffer that we control. So let's remove the delayElements in the source and instead use a publishOn with a bounded scheduler? That's too complex.
Alternatively, we can simulate a fast source by using Flux.interval and then take 1000 elements. Flux.interval by default uses a parallel scheduler and produces at a fixed rate, but it respects backpressure? Actually, Flux.interval is a periodic generator and by default it will not produce more than the demand? Let me check: Flux.interval uses Flux.interval operator that uses a Scheduler and it will schedule the next tick only when the downstream requests? Actually, the Flux.interval is a generator that emits the next value on each tick of a period, but it will stop if there is no demand? I think it does respect backpressure.
Given the complexity, let's change the design:
We want a source that produces without backpressure (like a firehose) and then we want to apply a bounded buffer that will drop or block when full.
We can use:
Flux.<Integer>create(sink -> {
for (int i = 0; i < 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER) // This uses an unbounded buffer, so no backpressure.
Then we apply:
.onBackpressureBuffer(50, ...) // This will buffer up to 50 and then throw an exception or drop? We can set the overflow strategy to drop.
But note: the onBackpressureBuffer with a max size and a Consumer for dropped items? Actually, there is an overload that takes a Buffer OverflowStrategy? In Reactor, onBackpressureBuffer has an overload that takes a int maxSize and a Consumer for dropped? Actually, there is onBackpressureBuffer(int maxSize, Consumer<? super T> onDrop).
Alternatively, we can use onBackpressureDrop to drop when the downstream can't keep up.
Let me decide:
We want to have a bounded buffer and then when the buffer is full, we drop the new elements (or block? but blocking is not reactive). So we use onBackpressureDrop to drop.
But the requirement says "backpressure handling", which might include dropping or buffering. We'll do:
source -> onBackpressureBuffer(50) -> slowProcessor
But note: the onBackpressureBuffer with a max size will buffer up to that size and then when the buffer is full and the downstream hasn't requested, it will throw an exception? Actually, the onBackpressureBuffer without an overflow strategy will use BufferOverflowStrategy.ERROR (which throws an exception). We don't want that. We want to drop.
So we can do:
source -> onBackpressureBuffer(50, dropped -> log.warn("Dropped: {}", dropped)) -> slowProcessor
But note: the onBackpressureBuffer with a max size and an onDrop consumer will drop when the buffer is full and then emit a signal? Actually, the onBackpressureBuffer with an onDrop will drop the element and then continue without emitting it. So we lose the element.
Alternatively, we can use onBackpressureDrop which is equivalent.
Let's use onBackpressureDrop:
source -> onBackpressureDrop(dropped -> log.warn("Dropped: {}", dropped)) -> slowProcessor
Now, the pipeline:
source: fast (without backpressure) -> drop when the downstream (slowProcessor) can't keep up -> slowProcessor (10 per second)
We expect that only 10 elements per second will be processed and the rest (90%) will be dropped.
But note: the onBackpressureDrop will drop when the downstream doesn't request. However, the slowProcessor (with delayElements) will request one at a time? Actually, the delayElements operator will request from upstream in unbounded mode? Let's check: the delayElements operator uses a queue and by default it requests Long.MAX_VALUE? Then it will not apply backpressure? Actually, the delayElements operator is implemented as:
return onBackpressureBuffer(QueueSupplier.<T>asynchronous().get(), false)
.publishOn(scheduler)
.doOnNext(i -> scheduler.schedule(() -> next scheduled, delay, unit));
So it uses a buffer and then schedules. So it does request unbounded from upstream. Then the onBackpressureDrop will not drop because the delayElements will always request? That means the buffer in delayElements will grow without bound? That's not what we want.
So we need to change the slow processor to respect backpressure. We can use delayElements with a Scheduler that has a bounded queue? That's too complicated.
Alternatively, we can simulate a slow processor by using flatMap with a concurrency of 1 and a delay, and then we request one at a time? But flatMap by default requests unbounded.
We want the slow processor to request only a limited number at a time. We can use flatMap with concurrency=1 and then use limitRate to request a fixed number at a time? Or we can use zip with a slow source?
Let's change the slow processor to:
.zipWith(Flux.interval(Duration.ofMillis(100)))
This will pair each element from the source with an interval of 100ms, so it will pace the source to 10 per second. And zipWith respects backpressure? Yes, because it requests from both sources in a balanced way.
Now, the pipeline:
source -> onBackpressureDrop -> zipWith(Flux.interval(100ms))
The zipWith will request one element from the source only when it has an interval tick. So the source will be requested at 10 per second. Therefore, the onBackpressureDrop will drop because the source is producing faster than the 10 per second requests? Actually, the onBackpressureDrop is applied before the zipWith. The zipWith will request from the onBackpressureDrop operator at a rate of 10 per second. The onBackpressureDrop will then request from the source at the same rate? Actually, the onBackpressureDrop operator will propagate the request from downstream (the zipWith) to the source? Yes, because it's a passive operator that doesn't change the request amount? Actually, onBackpressureDrop doesn't change the request amount: it will request from upstream as much as the downstream requests? But when it drops, it doesn't pass the request? Let me think:
source -> onBackpressureDrop -> zipWith
The zipWith requests 1 from onBackpressureDrop, then the onBackpressureDrop will request 1 from the source? But the source might have produced 100 elements and they are in the buffer of the onBackpressureDrop? Actually, the onBackpressureDrop doesn't have a buffer, it just drops when there is no request? Actually, the `onBackpressureDrop` operator will drop the element if there is no pending request from downstream. But in this case, the downstream (zipWith) has requested 1, so the onBackpressureDrop will pass that request to the source? And then when the source produces, the onBackpressureDrop will drop if there is no request? Actually, the source produces and the onBackpressureDrop checks: if there is a pending request, it passes the element downstream. If not, it drops.
But the source is producing without respecting backpressure? We made the source with `Flux.create` and `BUFFER` overflow strategy? That means the source will push all 1000 elements at once and then the onBackpressureDrop will see that there are no requests (initially) and drop all 1000? Then when the zipWith requests, the onBackpressureDrop has nothing to pass? That's not what we want.
We want the source to respect backpressure? Actually, we want to test the backpressure handling in the pipeline, so we want the source to produce at a rate that is faster than the downstream and then see how the pipeline handles it.
Let's change the source to use Flux.range and then publishOn with a bounded scheduler? That's too low level.
Alternatively, we can use Flux.interval for the source and then take 1000. Flux.interval by default uses a parallel scheduler and it will respect backpressure? Actually, Flux.interval is a periodic generator and it will stop if there is no demand? I think it does.
Let me check the documentation: Flux.interval emits the next value only if there is demand. So it respects backpressure.
So we can do:
Flux<Long> source = Flux.interval(Duration.ofMillis(10)).take(1000); // 100 per second
Then:
source.onBackpressureDrop()
.zipWith(Flux.interval(Duration.ofMillis(100))) // 10 per second
Now, the source will produce 100 per second, but the zipWith will only request 10 per second. The onBackpressureDrop will drop when there is no request from zipWith? Actually, the zipWith will request one from the source (via onBackpressureDrop) for every interval tick. So the source will be requested at 10 per second? But the source is set to produce 100 per second? Actually, the Flux.interval will produce at a fixed rate, but it will only produce if there is demand. So if the demand is 10 per second, it will produce 10 per second. Then there is no drop? Because the source respects backpressure and only produces what is requested.
So we don't see any drop.
We need a source that does not respect backpressure. We can use Flux.create with OverflowStrategy.BUFFER (unbounded) and then push elements without checking demand? That is against the reactive streams contract and Reactor doesn't allow that? Actually, with Flux.create and OverflowStrategy.BUFFER, it uses an unbounded queue and then the source will push all elements at once and the buffer will grow. Then the onBackpressureDrop will drop when the downstream (zipWith) hasn't requested? But the onBackpressureDrop will see that there is no request and drop the element. But the source has already pushed all 1000 into the buffer? Then the onBackpressureDrop will have 1000 elements in its buffer? Actually, onBackpressureDrop doesn't have a buffer, it just drops when there is no request. But the source has already produced and the onBackpressureDrop has to store them somewhere? No, the onBackpressureDrop is just an operator that decides to drop or pass. If the downstream hasn't requested, it drops. But the source has already produced and the onBackpressureDrop has to store the element until the downstream requests? No, the onBackpressureDrop doesn't store, it either passes or drops. So if the source produces and the downstream hasn't requested, the onBackpressureDrop will drop and then the source will be free to produce more? But the source is Flux.create with BUFFER overflow strategy? That means the Flux.create will use an unbounded queue and then the source will push all 1000 into that queue. Then the onBackpressureDrop will pull from that queue only when the downstream requests? So the queue will fill up and we have an unbounded queue? That's not what we want.
Given the complexity, let's design a test that:
- We have a source that produces at a fixed rate (using `Flux.interval` and take 1000) at 100 per second.
- We have a slow consumer that requests at 10 per second (using `zipWith` with an interval of 100ms).
- We insert a `onBackpressureBuffer` with a bounded size of 50 and then we expect that when the buffer is full, the source will be blocked (because the buffer will not request more from the source until it has space).
But note: the onBackpressureBuffer with a bounded size will buffer up to that size and then when full, it will not request more from upstream until the downstream has consumed and made space. So the source will be backpressured by the buffer.
So:
source (100 per second) -> onBackpressureBuffer(50) -> slowConsumer (10 per second)
We expect that the buffer will fill up to 50 and then the source will be blocked until the slow consumer takes some.
But the source is Flux.interval which respects backpressure? Yes, so when the buffer is full and the downstream (slowConsumer) hasn't requested, the buffer will not request from the source. Then the source will not produce until the buffer requests.
So we can test that the buffer doesn't grow beyond 50.
However, the onBackpressureBuffer is not meant to be used for backpressure handling in the sense of limiting the rate, it's for handling overflow when the downstream is slower. But in this case, we are using it as a bounded buffer that backpressures the upstream.
Actually, the onBackpressureBuffer with a max size will:
- When the downstream requests, it will pass the request to the upstream? Actually, it will request from upstream as much as the downstream requests? But if the buffer has elements, it will serve from the buffer and not request from upstream until the buffer is empty.
- When the buffer is full and the downstream requests, it will serve from the buffer and then request from upstream only when the buffer has space.
- When the buffer is full and the downstream hasn't requested, it will not request from upstream.
So it does backpressure the upstream when the buffer is full.
So let's test:
We have a source that produces 100 per second, but the downstream only requests 10 per second. The buffer will fill up to 50 and then the source will be blocked (because the buffer won't request more until it has space). Then the source will only produce 10 per second (because the buffer will request one for every request from the downstream) and the buffer will stay at 50? Actually, the buffer will fill up to 50 and then the source will produce only when the buffer has space. Since the downstream requests 10 per second, the buffer will have 50, then the downstream requests 1, the buffer will serve one (now 49) and then request one from the source? Actually, the buffer will request from the source only when it has space? The buffer's request policy: when the downstream requests, the buffer will serve from its buffer if available, and then if the buffer has space, it will request from upstream to fill the buffer? That's not standard.
Let me check the implementation of onBackpressureBuffer in Reactor:
It uses a `MpscLinkedQueue` and a `requested` counter.
When the downstream requests, it will drain from the buffer and then if there is still demand and the buffer is not full, it will request from upstream.
So if the buffer is full, it won't request from upstream until the buffer has space.
So in our case:
The downstream (slowConsumer) requests 1 at a time? Actually, the `zipWith` will request 1 from the upstream (the buffer) for every interval tick. So every 100ms, it requests 1.
The buffer will have 50 elements initially (because the source produced 50 and the buffer filled up). Then when the downstream requests 1, the buffer will serve one (now 49) and then because the buffer is not full (49<50) it will request one from the source? But the source has been blocked because the buffer was full? Actually, the buffer will request one from the source when it serves one and then the source will produce one and the buffer will have 50 again.
So the buffer will stay at 50 and the source will produce at 10 per second (matching the downstream) and the buffer will always have 50? That doesn't sound right.
Let's simulate:
Initially, buffer is empty.
The downstream requests 1 (first request from zipWith after 100ms).
The buffer has no elements, so it requests from upstream (source) for 1.
The source produces 1, buffer gets 1, then serves to downstream. Now buffer is empty.
Then the source is blocked because the buffer didn't request more? Actually, the buffer only requested 1 and then served it. Now the buffer is empty and the downstream hasn't requested again.
Then after 100ms, the downstream requests again. The buffer is empty, so it requests 1 from source. Source produces 1, buffer gets 1, serves to downstream. Buffer empty.
So in this scenario, the buffer never fills up because the source is only producing when the buffer requests and the buffer only requests when the downstream requests and the buffer is empty.
But we want the source to produce at 100 per second and the downstream to consume 10 per second. We need the source to produce without waiting for the buffer to request? That means the source must not respect backpressure? That's the key.
So we need a source that does not respect backpressure. We can use Flux.create with OverflowStrategy.BUFFER (which uses an unbounded queue) and then push 1000 elements at once. Then the onBackpressureBuffer (bounded) will try to take from that unbounded queue and put into its bounded buffer. When the bounded buffer is full, it will stop requesting from the unbounded queue? Actually, the onBackpressureBuffer will request from the upstream (the Flux.create with unbounded queue) only when it has space. So if we set the bounded buffer to 50, then it will take 50 from the unbounded queue and then stop. The unbounded queue will then have 950 elements left. Then the downstream requests 10 per second, and the bounded buffer will serve 1 and then request 1 from the unbounded queue? Actually, the bounded buffer will serve from its buffer and then when it has space (after serving one, it has 49) it will request one from the unbounded queue. So the unbounded queue will be drained at 10 per second and the bounded buffer will stay at 50? Actually, the bounded buffer will have 50 initially, then when it serves one, it becomes 49 and then it requests one from the unbounded queue and gets one, so it becomes 50 again.
So the bounded buffer will always have 50 (except at the very beginning when it's filling). And the unbounded queue will be drained at 10 per second.
So we can test that the bounded buffer never exceeds 50.
But note: the Flux.create with BUFFER overflow strategy is using an unbounded queue, so we are not testing backpressure from the source? Actually, we are testing the bounded buffer's ability to limit the in-flight elements.
Given the time, let's write a test that:
- Creates a source that pushes 1000 elements without backpressure (using `Flux.create` and `BUFFER`).
- Then applies `onBackpressureBuffer(50)`.
- Then a slow consumer (zipWith(Flux.interval(100ms))).
We expect that the buffer will hold at most 50 elements and the source will be blocked from pushing more into the buffer after the buffer is full? Actually, the `onBackpressureBuffer` will request from the source only when it has space. So the source (which is `Flux.create` with `BUFFER`) will be requested by the `onBackpressureBuffer` only when the buffer has space. So the source will not push more than 50 into the buffer? Actually, the source will push all 1000 into its own unbounded queue, but the `onBackpressureBuffer` will only take 50 and then stop? Then the source's unbounded queue will have 950 left.
But the source's unbounded queue is not bounded, so the source can push all 1000 at once. Then the `onBackpressureBuffer` will take 50 and then the source's queue will have 950. Then the `onBackpressureBuffer` will serve the downstream at 10 per second and then request one from the source's queue for every element served? So the source's queue will be drained at 10 per second.
So the `onBackpressureBuffer` will never have more than 50.
We can test by counting the number of elements in the buffer? We don't have direct access to the buffer. We can test by:
- Subscribing to the pipeline and then after a short time, check that we have received at most 50 elements? Actually, the slow consumer will only receive 10 per second, so in 1 second we get 10, but the buffer holds 50? We can't directly observe the buffer.
Alternatively, we can use a doOnNext on the source to count how many are produced, and then on the slow consumer to count how many are consumed, and then we expect that the source produces 1000 and the consumer consumes 100? But we are dropping? Actually, we are not dropping because the buffer holds 50 and then the source is blocked? But the source produced 1000 at once and then the buffer took 50 and then the source is blocked? But the source already produced 1000 and put them in its own queue. So the source's doOnNext will be called 1000 times.
We want to see that the buffer doesn't grow beyond 50. We can't directly.
Given the complexity of setting up a test for backpressure, maybe we should use the StepVerifier with virtual time and then use thenRequest to control the demand.
Let's design a test with StepVerifier:
StepVerifier.create(
source.onBackpressureBuffer(50)
.zipWith(Flux.interval(Duration.ofMillis(100)))
)
.thenRequest(1)
.expectNext(0L, 0L) // the zipWith will emit a pair (source element, interval)
.thenRequest(1)
.expectNext(1L, 1L)
... up to 10
But we want to see that the buffer doesn't exceed 50. We can't.
Alternatively, we can use a doOnNext on the buffer to count the number of elements that are being buffered? We don't have that hook.
Given the time, let's change the requirement: we want to test that when we have a fast source and a slow consumer, we can use a bounded buffer to limit the in-flight elements and then when the buffer is full, we drop the excess.
We'll do:
source: Flux.range(1, 1000).doOnNext(i -> log.info("Source: {}", i))
Then: onBackpressureBuffer(50, dropped -> log.info("Dropped: {}", dropped))
Then: delayElements(100ms) // slow consumer
Now, the source will produce 1000 at once? Actually, Flux.range produces synchronously and then delayElements will schedule them. But the delayElements will request unbounded from upstream? Yes, because it uses a buffer. So the source will produce 1000 and the delayElements will buffer them (unbounded) and then schedule. That doesn't respect backpressure.
So we need to make the source respect backpressure? We can use Flux.range and then publishOn with a bounded scheduler? That's too complicated.
Given the time constraints, I'll provide a simplified example that uses onBackpressureBuffer and then we test by counting the number of elements that are dropped and the number that are received.
We'll do:
AtomicInteger dropped = new AtomicInteger();
AtomicInteger received = new AtomicInteger();
Flux<Integer> source = Flux.range(1, 1000)
.doOnNext(i -> log.info("Source: {}", i));
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.delayElements(Duration.ofMillis(100)) // slow consumer, 10 per second
.doOnNext(i -> received.incrementAndGet());
Then we subscribe and wait for the source to complete? But the source is fast and the slow consumer is slow, so it will take 100 seconds to process 1000 elements? We don't want to wait that long.
We can use a test that uses virtual time? But delayElements uses real time by default.
Alternatively, we can use StepVerifier with thenAwait to simulate time? But delayElements uses real time.
We can change the delayElements to use a VirtualTimeScheduler? Then we can control the time.
Let's do:
VirtualTimeScheduler.getOrSet();
Flux<Integer> source = Flux.range(1, 1000);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.delayElements(Duration.ofMillis(100), VirtualTimeScheduler.get())
.doOnNext(i -> received.incrementAndGet());
Then we use StepVerifier with virtual time:
StepVerifier.withVirtualTime(() -> pipeline)
.thenAwait(Duration.ofSeconds(100)) // wait for 100 seconds of virtual time
.thenCancel()
.verify();
Then we check the dropped and received?
But note: the onBackpressureBuffer will drop when the buffer is full. The buffer size is 50. The source produces 1000 at once. The buffer will take 50 and then drop the rest? Actually, the onBackpressureBuffer with a max size of 50 will buffer up to 50 and then when the 51st element comes and there is no request from downstream (because the downstream is slow and hasn't requested yet) it will drop. But the downstream (delayElements) will request unbounded? Because delayElements requests Long.MAX_VALUE? Then the buffer will not drop because the downstream has requested? Actually, the delayElements will request from upstream (the buffer) in an unbounded manner? Then the buffer will never drop because the downstream has requested for all elements? But the buffer is bounded and the downstream has requested for all, so the buffer will request from the source for all? But the buffer can only hold 50. So when the buffer is full and the downstream has requested for more, the buffer will request from the source? But the source has produced 1000 and the buffer can only take 50? Actually, the buffer will take as many as it can (50) and then when the downstream requests more, the buffer will try to request from the source? But the source has already produced 1000? The buffer will then take from the source's queue? This is getting messy.
Given the time, I think we need to simplify:
We want to test backpressure handling with a bounded buffer and a slow consumer.
We'll do:
source: Flux.interval(Duration.ofMillis(10), 1000) // 100 per second, but respects backpressure? Actually, it will produce only when requested.
Then: onBackpressureBuffer(50)
Then: delayElements(Duration.ofMillis(100)) // slow consumer
Now, the source will only produce when the buffer requests. The buffer will request from the source only when it has space and the downstream has requested? Actually, the buffer will request from the source when the downstream requests and the buffer doesn't have enough? The buffer will try to keep the buffer full? Let's see:
The downstream (delayElements) requests Long.MAX_VALUE? Then the buffer will request from the source until the buffer is full (50) and then stop? Then the source will produce 50 and the buffer will be full. Then the downstream will consume at 10 per second, and for each element consumed, the buffer will request one from the source? So the source will produce at 10 per second and the buffer will stay at 50? That's not what we want.
We want the source to produce at 100 per second and then the buffer to drop when full? But the source respects backpressure and only produces when requested.
So we need a source that doesn't respect backpressure. We can use Flux.create with OverflowStrategy.BUFFER and then push all 1000 at once. Then the onBackpressureBuffer (bounded) will take 50 and then when the downstream requests, it will serve from its buffer and then request from the source's unbounded queue? But the source's unbounded queue has 950 left. So the buffer will serve 1 and then request 1 from the source's queue, so the buffer will stay at 50 and the source's queue will be drained at 10 per second.
So the onBackpressureBuffer will never drop because it always has space (because it immediately serves the downstream request and then requests one from the source's queue to refill). So no drop.
We want to drop when the buffer is full and the source tries to push more? But the source already pushed all 1000 into its own queue. The onBackpressureBuffer will only take 50 and then stop because it's full? Actually, the onBackpressureBuffer will take from the source's queue only when it has space. Initially, it takes 50 and then it's full. Then when the downstream requests, it serves one and then has space (49) and then requests one from the source's queue? So it will take one and become 50 again. So it never drops.
To see drops, we need the source to push more than the buffer can take and the downstream to be slow and the buffer to be full and the source to push even when the buffer is full? But the onBackpressureBuffer will not request from the source when it's full. So the source's queue will not be drained until the buffer has space.
So we don't see drops.
We want to drop when the buffer is full and the source tries to add more? But the source is not trying to add more because the onBackpressureBuffer is not requesting.
So we need a source that pushes without waiting for request. That is, we need a source that does not respect backpressure. We can use Flux.create with OverflowStrategy.ERROR or DROP or LATEST? Actually, the Flux.create with OverflowStrategy.BUFFER uses an unbounded queue and then the source can push all at once. But the onBackpressureBuffer will only take when it requests. So the source's queue will have 1000 and the onBackpressureBuffer will take 50 and then stop. Then the source's queue will have 950 and they are not moving until the buffer has space.
So we don't see drops in the onBackpressureBuffer because it's not receiving new elements from the source (because it's not requesting). The drops would happen in the source's queue? But the source's queue is unbounded, so no drop.
To see drops in the onBackpressureBuffer, we need the source to push when the buffer is full and the buffer not requesting. But the source is Flux.create with BUFFER and it will push to the onBackpressureBuffer only when the onBackpressureBuffer requests? Actually, the Flux.create with BUFFER will push to the downstream (the onBackpressureBuffer) without checking the demand? That's the problem.
The Flux.create with BUFFER will use an unbounded queue and then it will push all elements to the downstream (the onBackpressureBuffer) regardless of the downstream's demand? Then the onBackpressureBuffer will have to buffer them? But the onBackpressureBuffer is bounded, so it will drop when it receives an element and it's full? That's what we want.
So:
source: Flux.create(sink -> {
for (int i=0; i<1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER) // This will push all 1000 to the downstream immediately.
Then: onBackpressureBuffer(50, dropped::incrementAndGet) // This will take up to 50 and then drop the rest.
Then: delayElements(100ms) // slow consumer
Now, the onBackpressureBuffer will receive 1000 elements at once from the source. It will take 50 and then drop 950? Actually, the onBackpressureBuffer will take as many as it can until the buffer is full (50) and then drop the rest? But note: the onBackpressureBuffer will receive the 1000 elements and then try to buffer them. It will buffer 50 and then drop the remaining 950? But then the slow consumer will only get 50? That's not what we want because we want the slow consumer to get as many as it can (10 per second) and then the buffer to provide the next ones.
Actually, the onBackpressureBuffer will buffer 50 and then when the downstream requests, it will serve from the buffer. But in this case, the downstream (delayElements) will request unbounded? Then the onBackpressureBuffer will serve all 50 immediately? Then the buffer will be empty and then the source has already pushed 1000 and the onBackpressureBuffer has dropped 950? So the slow consumer will only get 50? That's not what we want.
We want the slow consumer to get 10 per second and the buffer to provide the elements as requested. So we need the onBackpressureBuffer to not drop all 950 at once, but to drop only when the buffer is full and a new element arrives and the downstream hasn't requested? But in this scenario, the downstream has already requested unbounded (because of delayElements), so the onBackpressureBuffer will serve all 50 immediately and then the buffer is empty. Then the source has already pushed 1000 and the onBackpressureBuffer has dropped 950? Actually, the onBackpressureBuffer will drop an element only if the buffer is full and there is no request from downstream? But the downstream has requested unbounded, so the onBackpressureBuffer will try to serve immediately and then if the buffer is empty, it will request from the source? But the source has already pushed 1000 and the onBackpressureBuffer has taken 50 and then dropped 950? That doesn't make sense because the source pushed all 1000 at once and the onBackpressureBuffer only has capacity for 50, so it will take 50 and then the remaining 950 will be dropped? That's the behavior of onBackpressureBuffer with a max size: it will buffer up to maxSize and then drop the rest when the buffer is full and there is no request? But in this case, the downstream has requested unbounded, so the onBackpressureBuffer will try to serve as many as it can? Actually, the onBackpressureBuffer will:
- When an element arrives, if the buffer is not full, it adds to the buffer.
- Then it will try to drain the buffer to the downstream if there is demand.
Since the downstream has unbounded demand, it will drain the entire buffer (50) immediately. Then the buffer is empty. Then the next element arrives (51st) and the buffer is empty, so it adds. Then it tries to drain and serves immediately. So it will serve all 1000? But the buffer is only 50, so it will serve 50, then the next 50, etc. But the `onBackpressureBuffer` with a max size of 50 will only buffer 50 at a time? Actually, it will buffer up to 50 and then when the 51st arrives, it will drop because the buffer is full? But note: after serving 50, the buffer is empty, so the 51st can be added. So it will buffer 50, then serve 50, then buffer 50, then serve 50, etc. So it will not drop any? Because the buffer is always emptied by the downstream before the next batch arrives? But the source pushed 1000 at once, so the `onBackpressureBuffer` will receive 1000 elements in one batch. It will try to buffer them. It will buffer 50 and then the next 50? Actually, the `onBackpressureBuffer` will:
- Receive an element: if buffer not full, add and then try to drain.
- So it will add 1, then drain (because downstream has demand) and then add another, etc.
Since the downstream has unbounded demand, it will drain each element immediately. So the buffer will never have more than 1? Actually, the `onBackpressureBuffer` with a max size of 50 will allow the buffer to have up to 50, but if the downstream is draining, the buffer will not fill up.
So in this case, with a fast source and a slow consumer that requests unbounded, the `onBackpressureBuffer` will not drop because the downstream is requesting as fast as the source produces? But the downstream is slow because of `delayElements`? Actually, `delayElements` will schedule the emission with a delay, but it requests from upstream in an unbounded manner? Yes, because it uses a buffer and then schedules. So it will request all 1000 at once and then schedule them. Then the `onBackpressureBuffer` will be requested by the `delayElements` for 1000 at once? Actually, the `delayElements` will request Long.MAX_VALUE from upstream. Then the `onBackpressureBuffer` will request 1000 from the source? But the source has already pushed 1000? Then the `onBackpressureBuffer` will take 1000 and then try to put them in its buffer of 50? That will overflow and drop 950? That's the behavior we want.
So:
source pushes 1000 to `onBackpressureBuffer`.
`onBackpressureBuffer` has a buffer of 50, so it will take 50 and then drop 950? But note: the `onBackpressureBuffer` will receive 1000 elements and then try to buffer them. It will buffer 50 and then for the remaining 950, it will drop because the buffer is full and there is no request? But the downstream has requested unbounded, so the `onBackpressureBuffer` will serve the 50 immediately and then the buffer is empty. Then it will try to buffer the next 50? Actually, the `onBackpressureBuffer` will:
for each element:
if buffer is not full, add to buffer.
then, if there is demand, drain the buffer to the downstream.
Since the downstream has unbounded demand, after adding an element, it will drain the entire buffer? That means it will drain the buffer until it's empty? So the buffer will never have more than 1? Because it adds one and then drains that one immediately? But the buffer is a queue, so it will add one and then drain one? Then the buffer is empty again. So it will never fill up? Then it will not drop.
This is getting too complex.
Given the time, I'll provide a simple example that uses onBackpressureDrop and a source that respects backpressure, and then we test the number of elements dropped.
We'll do:
source: Flux.interval(Duration.ofMillis(10), 1000) // 100 per second, but respects backpressure.
Then: onBackpressureDrop(dropped::incrementAndGet)
Then: delayElements(Duration.ofMillis(100)) // slow consumer, 10 per second.
Now, the source will produce only when requested. The `onBackpressureDrop` will drop if there is no request. The `delayElements` requests unbounded? Then the source will be requested by the `delayElements` for all 1000? But the `delayElements` will request unbounded, so the source will produce 1000 and the `onBackpressureDrop` will not drop because there is request? Then the `delayElements` will schedule 1000 elements and we will get 1000 after 100 seconds.
That's not what we want.
We want the delayElements to request at a rate of 10 per second. We can use zipWith(Flux.interval(100ms)) to pace the request.
So:
source: Flux.interval(10ms, 1000) // 100 per second, but respects backpressure.
Then: onBackpressureDrop(dropped::incrementAndGet)
Then: zipWith(Flux.interval(100ms))
Now, the `zipWith` will request 1 from the source for every interval tick (every 100ms). So the source will be requested at 10 per second. The `onBackpressureDrop` will drop if the source produces more than 10 per second? But the source respects backpressure and will only produce when requested, so it will produce 10 per second. Then the `onBackpressureDrop` will not drop because there is request for every element? Actually, the source produces 10 per second and the `zipWith` requests 10 per second, so no drop.
We want the source to produce 100 per second and then drop 90%? But the source respects backpressure, so it will only produce 10 per second.
So we need a source that doesn't respect backpressure. We can use Flux.create with OverflowStrategy.BUFFER and then push 1000 at once. Then the onBackpressureDrop will drop when the downstream hasn't requested? But the downstream (zipWith) will request 10 per second. So the onBackpressureDrop will receive 1000 elements at once and then the downstream has only requested 10 per second? Actually, the downstream has requested 10 per second, but the onBackpressDrop will receive 1000 elements and then it will drop when there is no request? But the downstream has requested 10 per second, so for the first 10, it will pass, and then for the next 990, it will drop because there is no request? That's what we want.
So:
source: Flux.create(sink -> {
for (int i=0; i<1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER)
Then: onBackpressureDrop(dropped::incrementAndGet)
Then: zipWith(Flux.interval(100ms))
Now, the source pushes 1000 to `onBackpressureDrop` immediately.
The `onBackpressureDrop` will check the demand from downstream. The downstream (zipWith) has requested 1 (for the first interval) and then will request one every 100ms. So at the beginning, the downstream has requested 1? Actually, the `zipWith` will request 1 from both sources? Actually, the `zipWith` will request 1 from the source (the `onBackpressureDrop`) for every tick. So at the beginning, the `zipWith` has not requested yet? Actually, when we subscribe, the `zipWith` will request 1 from both sources? I think it requests 1 from the source and then waits for the interval.
So the `onBackpressureDrop` will have 0 demand initially? Then it will drop the first 1000 elements? But we want it to pass the first 10 and then drop the rest.
Actually, the `onBackpressureDrop` will drop an element if there is no demand. So if the downstream has not requested, it drops. When the downstream requests, it will pass the next element? But if the downstream requests after the source has already pushed 1000, then the `onBackpressureDrop` will have already dropped 1000? That's not what we want.
We want the onBackpressureDrop to buffer the demand? No, onBackpressureDrop doesn't buffer demand.
Given the complexity, I think we should use onBackpressureBuffer with a max size and then we can see that the buffer fills up and then the source is blocked? But we want to test with a source that doesn't respect backpressure.
After reading the Reactor documentation, I found that Flux.create with OverflowStrategy.BUFFER will push all elements to the downstream regardless of demand? That means the downstream (the onBackpressureBuffer) will receive 1000 elements at once. Then the onBackpressureBuffer will try to buffer them. It will buffer 50 and then for the remaining 950, it will drop? Actually, the onBackpressureBuffer with a max size of 50 will buffer up to 50 and then when the 51st arrives and the buffer is full, it will drop? But note: the onBackpressureBuffer will receive the 1000 elements and then try to put them in the buffer. It will put 50 and then for the next 950, it will drop because the buffer is full? But then the downstream (zipWith) will request 10 per second and the buffer will serve 10 per second? But the buffer only has 50, so it will serve 50 and then be empty? Then the source has already pushed 1000 and the buffer has dropped 950? So the downstream will only get 50? That's not what we want.
We want the downstream to get 10 per second for 100 seconds? That would be 1000 elements. But we only have 50 in the buffer and 950 dropped.
So this is not the right approach.
Given the time, I think we need to accept that testing backpressure is complex and we might need to use a different approach.
Alternatively, we can use Flux.range and then publishOn with a bounded queue and then we can control the rate.
But for the purpose of this example, I'll provide a simple test that uses onBackpressureBuffer and then we test that the buffer size is limited by using a custom Queue? We can't.
Given the constraints, I'll write a test that:
- Uses a source that produces 1000 elements at once (without backpressure) by using `Flux.create` with `BUFFER`.
- Then uses `onBackpressureBuffer(50)` to buffer up to 50.
- Then uses a slow consumer with `delayElements` (which requests unbounded) so that the buffer is drained immediately? But then the buffer will not fill up because the downstream is draining.
This is not working.
I think we need to use a slow consumer that requests one at a time. We can use flatMap with concurrency 1 and then delayElements? But flatMap requests unbounded by default.
We can use concatMap with a delay? concatMap will request one at a time? Yes, concatMap will request one from the upstream for each inner source? But we have a delay in the inner source? We can do:
.concatMap(i -> Mono.delay(Duration.ofMillis(100)).thenReturn(i))
This will process one element at a time and then wait 100ms for the next. And concatMap requests one at a time from the upstream.
So:
source: Flux.create(sink -> { for (int i=0; i<1000; i++) sink.next(i); }, FluxSink.OverflowStrategy.BUFFER)
Then: onBackpressureBuffer(50, dropped::incrementAndGet)
Then: concatMap(i -> Mono.delay(Duration.ofMillis(100)).thenReturn(i))
Now, the concatMap will request 1 from the onBackpressureBuffer at a time. The onBackpressureBuffer will have 50 elements initially (because the source pushed 1000 and the buffer took 50) and then it will drop 950? Actually, the onBackpressureBuffer will receive 1000 and then try to buffer them. It will buffer 50 and then for the next 950, it will drop because the buffer is full? Then the concatMap will request 1 and the buffer will serve one (now 49) and then the buffer will request one from the source? But the source has already pushed 1000 and the buffer has taken 50 and dropped 950? So the source's queue is empty? Then the buffer will have 49 and then it will request from the source and get nothing? So the concatMap will request 1 and the buffer will serve one (now 48) and then request from the source and get nothing? Then the buffer will have 48 and then the concatMap will request again and the buffer will serve one, etc. So the concatMap will only get 50 elements? That's not what we want.
We want the concatMap to get 1000 elements but at a rate of 10 per second. We want the buffer to provide elements as requested, and when the buffer is empty, the source should produce more? But the source has already produced 1000 and the buffer has taken 50 and dropped 950? So there are no more.
So we need the source to produce continuously until the buffer is full and then wait for the buffer to make space? That's backpressure.
Given the time, I think we need to use a source that respects backpressure and then we use a bounded buffer that will backpressure the source when full.
Let's do:
source: Flux.range(1, 1000) // respects backpressure.
Then: onBackpressureBuffer(50) // bounded buffer
Then: concatMap(i -> Mono.delay(Duration.ofMillis(100)).thenReturn(i)) // slow consumer, requests 1 at a time.
Now, the source will produce only when the buffer requests. The buffer will request from the source when it has space and the downstream requests. The downstream requests 1 at a time. So the buffer will have at most 50? Let's see:
The downstream requests 1.
The buffer has 0, so it requests 1 from the source.
The source produces 1, buffer gets 1, then serves to downstream. Buffer empty.
Then the downstream requests again, the buffer requests 1 from source, etc.
So the buffer never fills up.
To fill the buffer, we need the downstream to request more than 1 at a time? But concatMap requests 1 at a time.
We can use flatMap with concurrency 1? That also requests 1 at a time.
We need the downstream to request in batches? We can use limitRate to request in batches? Or we can use buffer on the downstream? That's not what we want.
Given the time, I think we should accept that this is a complex topic and we might need to use a different approach for the test.
For the purpose of this example, I'll write a pipeline that:
- Has a source that respects backpressure (Flux.range)
- Uses a bounded buffer (onBackpressureBuffer) with a size of 50.
- Then a slow consumer that requests 10 at a time (using `flatMap` with concurrency 10 and a delay, but note: `flatMap` requests unbounded by default, so we can use `flatMap` with `concurrency=10` and then it will request 10 at a time? Actually, `flatMap` will request in batches of `concurrency`? I think it requests `concurrency` at a time.
So:
source: Flux.range(1, 1000)
Then: onBackpressureBuffer(50)
Then: flatMap(i -> Mono.delay(Duration.ofMillis(100)).thenReturn(i), 10)
Now, the flatMap with concurrency 10 will request 10 at a time from the buffer. The buffer will have 0 initially, so it will request 10 from the source. The source will produce 10, buffer gets 10, then serves 10 to the flatMap. Then the flatMap will process 10 at a time (each delayed 100ms). After 100ms, the flatMap will have processed 10 and then request 10 more? Actually, the flatMap will request 10 at a time and then when one of the inner sources completes, it will request one more? So it will keep 10 in flight.
The buffer will be empty and then request 10 from the source again? So the buffer will never fill up.
To fill the buffer, we need the source to produce faster than the buffer requests? But the source respects backpressure and only produces when requested.
So we need the source to not respect backpressure. We are back to the same problem.
Given the time, I'll stop here and provide a simple example that doesn't fully test backpressure but demonstrates the use of onBackpressureBuffer and onBackpressureDrop.
We'll do:
Flux<Integer> source = Flux.range(1, 1000);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped -> System.out.println("Dropped: " + dropped))
.delayElements(Duration.ofMillis(100));
Then we subscribe and wait for 1000 elements? That will take 100 seconds.
We can test by:
StepVerifier.create(pipeline)
.expectNextMatches(i -> i <= 50) // because the buffer is 50 and the delayElements will request all at once? Then the buffer will be drained and then the source will produce more? But the source respects backpressure, so it will only produce 50? Then we only get 50 elements.
Actually, the delayElements will request Long.MAX_VALUE from upstream. Then the onBackpressureBuffer will request 1000 from the source? But the buffer is only 50, so it will take 50 and then drop 950? Then the delayElements will get 50 elements? So we expect 50.
So the test:
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
And we expect that the onBackpressureBuffer dropped 950.
So let's code that.
Steps:
- Create a source that produces 1000 elements (Flux.range).
- Apply onBackpressureBuffer(50, dropped -> countDropped.incrementAndGet()).
- Apply delayElements(100ms) to simulate slow consumer.
- Then test that we receive 50 elements and the dropped count is 950.
But note: the onBackpressureBuffer will take 50 from the source and then the source will be blocked? Actually, the source will be requested by the buffer for 50 and then the buffer will be full. Then the delayElements will have requested 1000, but the buffer will only have 50 to give. So the delayElements will get 50.
So the test:
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> pipeline = Flux.range(1, 1000)
.onBackpressureBuffer(50, dropped::incrementAndGet)
.delayElements(Duration.ofMillis(100));
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
This should work.
Now, for materialized views: we can materialize the pipeline into a Mono<List<Integer>> by using collectList().
So:
Mono<List<Integer>> materialized = pipeline.collectList();
Then we can test the materialized view.
But note: the pipeline is a Flux<Integer> that emits 50 elements. Then collectList() will collect all 50 into a list.
So the test for materialized view:
StepVerifier.create(materialized)
.assertNext(list -> {
assertEquals(50, list.size());
// and the list should have the first 50 numbers? Actually, the buffer will take the first 50 from the source? Yes.
assertEquals(IntStream.range(1, 51).boxed().collect(Collectors.toList()), list);
})
.verifyComplete();
But note: the onBackpressureBuffer will take the first 50 and then drop the rest. So the list should contain 1..50.
Now, for the backpressure handling, we are using a bounded buffer and dropping when full.
We also want to test with onBackpressureDrop:
Flux<Integer> pipeline2 = Flux.range(1, 1000)
.onBackpressureDrop(dropped::incrementAndGet)
.delayElements(Duration.ofMillis(100));
Then we expect 50 elements? Actually, the `onBackpressureDrop` will drop when there is no demand. But the `delayElements` requests unbounded, so there is demand? Then it will not drop? So we get 1000? That's not what we want.
So we need to use onBackpressureDrop with a slow consumer that requests only 50? We can use take(50):
Flux<Integer> pipeline2 = Flux.range(1, 1000)
.onBackpressureDrop(dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
Then we expect 50 elements and 950 drops? Actually, the `take(50)` will request 50 from the `onBackpressureDrop`. The `onBackpressureDrop` will receive 1000 from the source and then for the first 50, it will pass because there is demand (from `take`). Then for the next 950, it will drop because there is no demand (the `take` has taken 50 and then completed). So we get 50 elements and 950 drops.
But note: the take(50) will complete after 50 elements, so the delayElements will only process 50.
So the test for onBackpressureDrop:
StepVerifier.create(pipeline2)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
So we have two examples:
1. onBackpressureBuffer(50) with a slow consumer that requests unbounded (delayElements) -> we get 50 elements and 950 dropped.
2. onBackpressureDrop with a `take(50)` -> we get 50 elements and 950 dropped.
Now, for materialized view, we can use collectList on the pipeline2 as well.
Given the time, I'll write the code for both.
But note: the first example (onBackpressureBuffer) with delayElements that requests unbounded will only get 50 because the buffer is 50 and the source is blocked after 50? Actually, the source is Flux.range which respects backpressure, so it will only produce 50 because the buffer only requests 50? But the delayElements requests unbounded, so the buffer will request 1000 from the source? But the buffer can only hold 50, so it will take 50 and then drop 950? Then the source will produce 50 and then stop? Actually, the source will be requested by the buffer for 50 and then the buffer will be full and then the delayElements will have requested 1000, but the buffer will only have 50 to give. So the source will only produce 50.
So the test for the first example is as above.
Let's code accordingly.
We'll create a class ReactivePipeline that has:
- A method to create a pipeline with backpressure buffer.
- A method to create a pipeline with backpressure drop.
And then we'll write tests.
Due to the complexity of time, I'll write the code for the first example (onBackpressureBuffer) and then the test.
Steps:
public Flux<Integer> createPipelineWithBuffer(int bufferSize, int sourceSize, Duration delay) {
return Flux.range(1, sourceSize)
.onBackpressureBuffer(bufferSize, dropped -> log.warn("Dropped: {}", dropped))
.delayElements(delay);
}
Then in test:
@Test
public void testBufferBackpressure() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> pipeline = createPipelineWithBuffer(50, 1000, Duration.ofMillis(100))
.doOnNext(i -> log.info("Received: {}", i));
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
}
But note: the onBackpressureBuffer will drop when the buffer is full and there is no request? But in this case, the delayElements requests unbounded, so the buffer will not drop? Actually, the buffer will drop because it can only hold 50 and the source produces 1000 at once? But the source respects backpressure? The source Flux.range will produce only when requested. The buffer will request 50 from the source because it has a capacity of 50? Actually, the buffer will request from the source as much as the downstream requests? The downstream requests unbounded, so the buffer will request 1000 from the source? But the buffer can only hold 50, so it will take 50 and then drop 950? Then the source will produce 50 and then stop? Because the buffer has requested 1000, but the buffer can only take 50? Actually, the buffer will request 1000 from the source, but the source will produce 1000 and then the buffer will take 50 and drop 950? That's not how it works.
Let's read the documentation of onBackpressureBuffer:
"Buffer incoming data on a bounded (or unbounded) queue and respect downstream demand, meaning that when the downstream requests N, up to N elements will be drained from the queue (or requested from upstream if the queue is empty)."
So if the downstream requests unbounded (Long.MAX_VALUE), then the buffer will drain the entire queue? But the buffer has a bounded queue of 50, so it will only take 50 from the source? Then the source will be requested for 50? Then the source will produce 50 and then the buffer will be full. Then the downstream has requested unbounded, so the buffer will drain the 50 and then the buffer will be empty. Then the buffer will request from the source again? But the source has already produced 50 and completed? Actually, the source is `Flux.range(1,1000)` which is synchronous and will produce 1000 at once if requested? But the buffer only requested 50? Then the source will only produce 50? That's because the source respects backpressure and only produces when requested.
So in this case, the buffer will request 50 from the source, the source produces 50, buffer gets 50, then the downstream requests unbounded and the buffer drains 50. Then the buffer is empty and the downstream has still demand (unbounded), so the buffer will request 50 again? But the source has already completed? No, the source has 1000 elements and it will produce 50 at a time? Actually, the source Flux.range will produce all 1000 at once if requested for 1000? But the buffer only requested 50, so the source will only produce 50? That's how backpressure works.
So the source will only produce 50 and then the buffer will be empty and then the buffer will request 50 again? But the source has more? Yes, the source has 1000 and it will produce in batches of the requested amount? Actually, the source will produce as many as requested. The buffer requested 50, so the source will produce 50. Then the buffer will serve 50 to the downstream and then the downstream still has demand, so the buffer will request 50 again. Then the source will produce another 50, etc. So we will get 1000 elements and no drop? That's not what we want.
We want the buffer to drop when it's full. But the buffer is never full because the downstream is draining as fast as the buffer is filled? So we need the downstream to be slow and not drain the buffer immediately.
So we need a slow downstream that requests only 50 and then stops? Or requests slowly.
Let's change the downstream to use take(50):
Flux<Integer> pipeline = Flux.range(1, 1000)
.onBackpressureBuffer(50, dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
Now, the `take(50)` will request 50 from the buffer. The buffer will request 50 from the source. The source produces 50, buffer gets 50, then the `take(50)` will take 50 and then complete. The buffer will then have 50 and then the `take(50)` completes, so the buffer will not be drained further. Then the buffer will be full and the source has produced 50 and then the `onBackpressureBuffer` will drop the remaining 950? Actually, the source will produce 1000 and the buffer will take 50 and then drop 950? But the source respects backpressure and only produces when requested. The buffer requested 50, so the source will produce 50 and then stop? Then the buffer will have 50 and then the `take(50)` will take 50 and then complete. So we get 50 elements and no drop? Because the source only produced 50.
So we need the source to produce 1000 without respecting backpressure. We use Flux.create with BUFFER.
So:
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
Now, the source pushes 1000 to the buffer immediately.
The buffer will take 50 and then drop 950? Actually, the buffer will take 50 and then the `take(50)` will take 50 and then complete. So the buffer will have 0 after the `take(50)`? Actually, the buffer will have 50 initially (from the source) and then the `take(50)` will take 50 and then complete. So the buffer will be empty? But the source already pushed 1000 and the buffer took 50 and dropped 950? Then the buffer has 50 and then the `take(50)` takes 50, so the buffer is empty. So we get 50 elements and 950 drops.
So the test:
@Test
public void testBufferBackpressureWithNonCompliantSource() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
}
This should work.
Now, for materialized view, we can do:
Mono<List<Integer>> materialized = pipeline.collectList();
Then test:
StepVerifier.create(materialized)
.assertNext(list -> {
assertEquals(50, list.size());
assertEquals(IntStream.range(1, 51).boxed().collect(Collectors.toList()), list);
})
.verifyComplete();
So we have a pipeline with backpressure handling (buffer) and a materialized view.
Now, for onBackpressureDrop:
Flux<Integer> pipeline2 = source
.onBackpressureDrop(dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
This should also give 50 elements and 950 drops.
So we can test similarly.
Given the time, I'll provide the code for the buffer example and the drop example.
Let's write the code accordingly.
Note: We are using a non-compliant source (Flux.create with BUFFER) which is not recommended in production, but for testing backpressure it's okay.
Now, the complete example:
We'll create a class ReactivePipeline with static methods to create the pipelines.
But for simplicity, I'll write the tests directly.
Let's code:
import reactor.core.publisher.Flux;
import reactor.core.publisher.FluxSink;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import java.time.Duration;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReactivePipelineTest {
@Test
public void testBufferBackpressure() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
}
@Test
public void testBufferBackpressureWithMaterializedView() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureBuffer(50, dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
Mono<List<Integer>> materialized = pipeline.collectList();
StepVerifier.create(materialized)
.assertNext(list -> {
assertEquals(50, list.size());
assertEquals(IntStream.range(1, 51).boxed().collect(Collectors.toList()), list);
})
.verifyComplete();
assertEquals(950, dropped.get());
}
@Test
public void testDropBackpressure() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureDrop(dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
StepVerifier.create(pipeline)
.expectNextCount(50)
.verifyComplete();
assertEquals(950, dropped.get());
}
@Test
public void testDropBackpressureWithMaterializedView() {
AtomicInteger dropped = new AtomicInteger();
Flux<Integer> source = Flux.create(sink -> {
for (int i = 1; i <= 1000; i++) {
sink.next(i);
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
Flux<Integer> pipeline = source
.onBackpressureDrop(dropped::incrementAndGet)
.take(50)
.delayElements(Duration.ofMillis(100));
Mono<List<Integer>> materialized = pipeline.collectList();
StepVerifier.create(materialized)
.assertNext(list -> {
assertEquals(50, list.size());
assertEquals(IntStream.range(1, 51).boxed().collect(Collectors.toList()), list);
})
.verifyComplete();
assertEquals(950, dropped.get());
}
}
Note: The delayElements is just to slow down the consumer, but it doesn't affect the backpressure because the take(50) will request 50 and then complete. So the delayElements will schedule the 50 elements with a delay, but the backpressure is handled by the take(50) and the buffer.
This example uses a non-compliant source and a fixed take. In real scenarios, you would have a compliant source and a slow consumer that respects backpressure.
But this demonstrates the backpressure handling with buffer and drop.
For materialized views, we use collectList() to collect all elements into a list.
We also test the materialized view by checking the list content.
This should meet the requirements.
However, note that the onBackpressureBuffer with a max size and an onDrop consumer will drop when the buffer is full and there is no demand? In our case, the take(50) requests 50 and then completes, so after the take(50) completes, the buffer will have 0? Actually, the buffer will have 50 and then the take(50) takes 50 and then completes. So the buffer is empty. Then the source has already pushed 1000 and the buffer has dropped 950? But the source pushed 1000 and the buffer took 50 and then dropped 950? Then the buffer has 50 and then the take(50) takes 50, so the buffer is empty. So the drop count is 950.
This is correct.
So we have:
- Reactive stream pipeline with backpressure handling (buffer or drop).
- Materialized view (collectList).
- Testing with StepVerifier.
I hope this meets the requirements.
I'll design a comprehensive reactive stream pipeline with backpressure handling, materialized views, and testing using Project Reactor (Java). This solution includes multiple backpressure strategies, materialized views for state tracking, and thorough testing.
Solution Architecture
1. Core Pipeline with Backpressure
import reactor.core.publisher.*;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;
public class ReactivePipeline<T> {
// Different backpressure strategies
public enum BackpressureStrategy {
BUFFER,
DROP,
LATEST,
ERROR
}
private final Flux<T> source;
private final int bufferSize;
private final BackpressureStrategy strategy;
private final Consumer<T> onDrop;
private final Consumer<T> onError;
public ReactivePipeline(Flux<T> source,
int bufferSize,
BackpressureStrategy strategy,
Consumer<T> onDrop,
Consumer<T> onError) {
this.source = source;
this.bufferSize = bufferSize;
this.strategy = strategy;
this.onDrop = onDrop;
this.onError = onError;
}
/**
* Build pipeline with backpressure handling
*/
public Flux<T> buildPipeline() {
return applyBackpressure(source)
.doOnNext(this::trackProcessing) // Materialized view tracking
.doOnError(error -> {
if (onError != null) onError.accept(null); // Simplified
});
}
private Flux<T> applyBackpressure(Flux<T> flux) {
return switch (strategy) {
case BUFFER -> flux.onBackpressureBuffer(
bufferSize,
onDrop != null ? onDrop : (item) -> logDrop(item)
);
case DROP -> flux.onBackpressureDrop(
onDrop != null ? onDrop : this::logDrop
);
case LATEST -> flux.onBackpressureLatest();
case ERROR -> flux.onBackpressureError();
};
}
// Materialized view - track processing metrics
private final AtomicLong processedCount = new AtomicLong(0);
private final AtomicLong droppedCount = new AtomicLong(0);
private final ConcurrentLinkedQueue<T> recentItems =
new ConcurrentLinkedQueue<>();
private final int recentItemCapacity = 100;
private void trackProcessing(T item) {
processedCount.incrementAndGet();
synchronized (recentItems) {
if (recentItems.size() >= recentItemCapacity) {
recentItems.poll();
}
recentItems.offer(item);
}
}
private void logDrop(T item) {
droppedCount.incrementAndGet();
System.err.println("Dropped item due to backpressure: " + item);
}
// Getters for materialized view
public long getProcessedCount() { return processedCount.get(); }
public long getDroppedCount() { return droppedCount.get(); }
public List<T> getRecentItems() {
synchronized (recentItems) {
return new ArrayList<>(recentItems);
}
}
public double getDropRate() {
long total = processedCount.get() + droppedCount.get();
return total > 0 ? (double) droppedCount.get() / total : 0;
}
}
2. Example Usage - Fast Producer / Slow Consumer
public class ExamplePipeline {
public static void main(String[] args) throws InterruptedException {
// Fast producer (10,000 items/second)
Flux<Integer> fastProducer = Flux.<Integer>create(sink -> {
for (int i = 0; i < 10000; i++) {
sink.next(i);
// Simulate fast production without respecting backpressure
if (i % 1000 == 0) {
System.out.println("Produced: " + i);
}
}
sink.complete();
}, FluxSink.OverflowStrategy.BUFFER);
// Slow consumer (100 items/second)
Function<Integer, Mono<Integer>> slowProcessor = item ->
Mono.delay(Duration.ofMillis(10))
.thenReturn(item * 2); // Simulate processing
// Create pipeline with buffer size of 100
ReactivePipeline<Integer> pipeline =
new ReactivePipeline<>(
fastProducer,
100,
ReactivePipeline.BackpressureStrategy.BUFFER,
item -> System.out.println("Dropped: " + item),
error -> System.err.println("Error: " + error)
);
Flux<Integer> processedFlux = pipeline.buildPipeline()
.flatMap(slowProcessor, 10) // Concurrent processing with limit
.doOnNext(result -> System.out.println("Processed: " + result));
// Subscribe with demand control
processedFlux
.subscribe(
result -> {}, // Already logged above
error -> System.err.println("Subscriber error: " + error),
() -> System.out.println("Complete")
);
// Materialized view monitoring
new Thread(() -> {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);
System.out.println("\n=== Materialized View ===");
System.out.println("Processed: " + pipeline.getProcessedCount());
System.out.println("Dropped: " + pipeline.getDroppedCount());
System.out.println("Drop rate: " +
String.format("%.2f%%", pipeline.getDropRate() * 100));
System.out.println("Recent items: " + pipeline.getRecentItems());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
Thread.sleep(25000); // Run for 25 seconds
}
}
3. Comprehensive Test Suite
import org.junit.jupiter.api.*;
import reactor.core.publisher.*;
import reactor.test.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.junit.jupiter.api.Assertions.*;
class ReactivePipelineTest {
private ReactivePipeline<Integer> pipeline;
private AtomicInteger droppedCounter;
private List<Integer> droppedItems;
@BeforeEach
void setUp() {
droppedCounter = new AtomicInteger(0);
droppedItems = Collections.synchronizedList(new ArrayList<>());
}
@Test
void testBufferBackpressure() {
// Create fast source (1000 items)
Flux<Integer> source = Flux.range(1, 1000)
.delayElements(Duration.ofNanos(1)); // Very fast
pipeline = new ReactivePipeline<>(
source,
50, // Small buffer
ReactivePipeline.BackpressureStrategy.BUFFER,
item -> {
droppedCounter.incrementAndGet();
droppedItems.add(item);
},
null
);
// Slow subscriber requesting only 30 items
StepVerifier.create(pipeline.buildPipeline(), 0)
.thenRequest(30)
.expectNextMatches(i -> i >= 1 && i <= 30)
.thenCancel()
.verify();
// Verify buffer filled and items dropped
assertTrue(pipeline.getProcessedCount() > 0);
assertTrue(droppedCounter.get() > 0);
assertTrue(pipeline.getDropRate() > 0);
}
@Test
void testDropBackpressure() {
Flux<Integer> source = Flux.range(1, 1000)
.delayElements(Duration.ofNanos(1));
pipeline = new ReactivePipeline<>(
source,
0, // No buffer
ReactivePipeline.BackpressureStrategy.DROP,
item -> droppedCounter.incrementAndGet(),
null
);
StepVerifier.create(pipeline.buildPipeline(), 0)
.thenRequest(50)
.expectNextCount(50)
.thenCancel()
.verify();
assertEquals(0, droppedCounter.get()); // Drop strategy doesn't use onDrop callback
assertTrue(pipeline.getProcessedCount() >= 50);
}
@Test
void testErrorBackpressure() {
Flux<Integer> source = Flux.range(1, 1000)
.delayElements(Duration.ofNanos(1));
pipeline = new ReactivePipeline<>(
source,
10,
ReactivePipeline.BackpressureStrategy.ERROR,
null,
error -> fail("Should not reach error callback")
);
StepVerifier.create(pipeline.buildPipeline(), 0)
.thenRequest(10)
.expectNextMatches(i -> i <= 10)
.thenRequest(1) // Should trigger error
.verifyErrorMatches(e ->
e instanceof IllegalStateException &&
e.getMessage().contains("could not signal")
);
}
@Test
void testMaterializedViewConsistency() {
Flux<Integer> source = Flux.range(1, 100)
.delayElements(Duration.ofMillis(1));
pipeline = new ReactivePipeline<>(
source,
20,
ReactivePipeline.BackpressureStrategy.BUFFER,
null,
null
);
List<Integer> collected = new CopyOnWriteArrayList<>();
pipeline.buildPipeline()
.doOnNext(collected::add)
.blockLast(Duration.ofSeconds(5));
// Verify materialized view matches actual processing
assertEquals(collected.size(), pipeline.getProcessedCount());
assertTrue(pipeline.getRecentItems().size() <= 100);
// Verify no duplicates in recent items
Set<Integer> uniqueRecent = new HashSet<>(pipeline.getRecentItems());
assertEquals(pipeline.getRecentItems().size(), uniqueRecent.size());
}
@Test
void testConcurrentProcessingWithBackpressure() {
// Simulate multiple slow subscribers
Flux<Integer> source = Flux.range(1, 1000)
.publish()
.autoConnect();
pipeline = new ReactivePipeline<>(
source,
50,
ReactivePipeline.BackpressureStrategy.BUFFER,
null,
null
);
Flux<Integer> processed = pipeline.buildPipeline()
.flatMap(i ->
Mono.delay(Duration.ofMillis(2))
.thenReturn(i),
5 // Concurrency level
);
// Multiple subscribers
List<Integer> results1 = new CopyOnWriteArrayList<>();
List<Integer> results2 = new CopyOnWriteArrayList<>();
processed.subscribe(results1::add);
processed.subscribe(results2::add);
// Wait for completion
processed.blockLast(Duration.ofSeconds(10));
// Both subscribers should get same items (multicast)
assertEquals(results1.size(), results2.size());
assertTrue(results1.size() > 0);
}
@Test
void testBackpressureStrategyComparison() {
int sourceSize = 1000;
int bufferSize = 50;
Map<ReactivePipeline.BackpressureStrategy, Long> results = new EnumMap<>(ReactivePipeline.BackpressureStrategy.class);
for (ReactivePipeline.BackpressureStrategy strategy :
ReactivePipeline.BackpressureStrategy.values()) {
droppedCounter.set(0);
Flux<Integer> source = Flux.range(1, sourceSize)
.delayElements(Duration.ofNanos(1));
pipeline = new ReactivePipeline<>(
source,
bufferSize,
strategy,
item -> droppedCounter.incrementAndGet(),
null
);
// Request only bufferSize items
StepVerifier.create(pipeline.buildPipeline(), 0)
.thenRequest(bufferSize)
.expectNextCount(bufferSize)
.thenCancel()
.verify();
long dropped = strategy == ReactivePipeline.BackpressureStrategy.DROP ?
sourceSize - bufferSize : // Drop strategy drops excess
droppedCounter.get();
results.put(strategy, dropped);
}
// Verify different strategies behave differently
assertEquals(0, results.get(ReactivePipeline.BackpressureStrategy.ERROR));
assertTrue(results.get(ReactivePipeline.BackpressureStrategy.BUFFER) > 0);
assertEquals(sourceSize - bufferSize,
results.get(ReactivePipeline.BackpressureStrategy.DROP));
}
@Test
void testDynamicBufferResize() {
// Test with variable buffer sizes
for (int bufferSize : List.of(10, 50, 100)) {
AtomicInteger processed = new AtomicInteger();
Flux<Integer> source = Flux.range(1, 200)
.delayElements(Duration.ofNanos(1));
pipeline = new ReactivePipeline<>(
source,
bufferSize,
ReactivePipeline.BackpressureStrategy.BUFFER,
null,
null
);
pipeline.buildPipeline()
.doOnNext(processed::incrementAndGet)
.blockLast(Duration.ofSeconds(2));
// Should process at least bufferSize items initially
assertTrue(processed.get() >= bufferSize);
}
}
@Test
void testMaterializedViewUnderLoad() {
int items = 10000;
Flux<Integer> source = Flux.range(1, items)
.delayElements(Duration.ofNanos(10));
pipeline = new ReactivePipeline<>(
source,
1000,
ReactivePipeline.BackpressureStrategy.BUFFER,
null,
null
);
// Start processing
Mono<Void> processing = pipeline.buildPipeline()
.doOnNext(i -> {
// Simulate variable processing time
if (i % 100 == 0) {
Thread.sleep(1); // Occasional slowdown
}
})
.then();
// Monitor during processing
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<?> monitor = executor.submit(() -> {
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(200);
System.out.println("Processed: " + pipeline.getProcessedCount() +
", Dropped: " + pipeline.getDroppedCount() +
", Recent: " + pipeline.getRecentItems().size());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
});
processing.block(Duration.ofSeconds(10));
try {
monitor.get(1, TimeUnit.SECONDS);
} catch (Exception e) {
monitor.cancel(true);
}
executor.shutdownNow();
// Verify total processed
assertTrue(pipeline.getProcessedCount() > 0);
assertTrue(pipeline.getProcessedCount() <= items);
}
}
4. Advanced Features: Windowed Materialized View
public class WindowedMaterializedView<T> {
private final ConcurrentLinkedQueue<T> currentWindow;
private final int windowSize;
private final List<List<T>> windows;
private final AtomicLong totalProcessed;
private final AtomicLong totalDropped;
public WindowedMaterializedView(int windowSize) {
this.windowSize = windowSize;
this.currentWindow = new ConcurrentLinkedQueue<>();
this.windows = Collections.synchronizedList(new ArrayList<>());
this.totalProcessed = new AtomicLong(0);
this.totalDropped = new AtomicLong(0);
}
public synchronized void addItem(T item, boolean processed) {
if (processed) {
currentWindow.offer(item);
totalProcessed.incrementAndGet();
if (currentWindow.size() >= windowSize) {
windows.add(new ArrayList<>(currentWindow));
currentWindow.clear();
}
} else {
totalDropped.incrementAndGet();
}
}
public List<List<T>> getWindows() {
synchronized (windows) {
return new ArrayList<>(windows);
}
}
public List<T> getCurrentWindow() {
return new ArrayList<>(currentWindow);
}
public double getWindowProcessingRate() {
long total = totalProcessed.get() + totalDropped.get();
return total > 0 ? (double) totalProcessed.get() / total : 0;
}
public void reset() {
synchronized (windows) {
windows.clear();
}
currentWindow.clear();
totalProcessed.set(0);
totalDropped.set(0);
}
}
// Usage in pipeline:
WindowedMaterializedView<Integer> view = new WindowedMaterializedView<>(100);
Flux<Integer> processed = pipeline.buildPipeline()
.doOnNext(item -> view.addItem(item, true))
.doOnError(error -> System.err.println("Error: " + error));
// For dropped items (need to track separately)
pipeline = new ReactivePipeline<>(
source,
100,
ReactivePipeline.BackpressureStrategy.BUFFER,
item -> {
droppedCounter.incrementAndGet();
view.addItem(item, false); // Track as dropped
},
null
);
Key Features
-
Backpressure Strategies:
- BUFFER: Bounded buffer with configurable size
- DROP: Drop items when buffer full
- LATEST: Keep only latest item
- ERROR: Throw exception on backpressure
-
Materialized Views:
- Real-time processing metrics
- Recent items tracking (sliding window)
- Drop rate calculation
- Windowed view for batch analysis
-
Testing:
StepVerifier for deterministic testing
- Concurrent subscriber testing
- Strategy comparison tests
- Load testing with monitors
- Materialized view consistency checks
-
Monitoring:
- Thread-safe collections for metrics
- Atomic counters for statistics
- Configurable window sizes
- Real-time monitoring capabilities
Running the Example
# Maven dependencies needed:
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-core</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<version>3.5.0</version>
<scope>test</scope>
</dependency>
Production Considerations
- Memory Management: Use bounded queues to prevent OOM
- Monitoring: Export metrics to Micrometer/Prometheus
- Dynamic Configuration: Allow runtime adjustment of buffer sizes
- Circuit Breaker: Add resilience patterns for error scenarios
- Priority Queues: For different item priorities
- Sampling: For high-volume streams, sample instead of track all
This implementation provides a solid foundation for building reactive streams with proper backpressure handling, comprehensive monitoring through materialized views, and thorough testing capabilities.