[
https://issues.apache.org/jira/browse/HADOOP-19918?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18143020#comment-18143020
]
ASF GitHub Bot commented on HADOOP-19918:
-----------------------------------------
Abhi0505-kinagi opened a new pull request, #8969:
URL: https://github.com/apache/hadoop/pull/8969
## HADOOP-19918 Reduce lock contention in MutableQuantiles.add()
This change addresses lock contention in `MutableQuantiles.add()` and
improves concurrent sample ingestion in `SampleQuantiles`.
The existing implementation serializes concurrent quantile updates through
synchronization, potentially making metrics collection a bottleneck under
high-concurrency workloads.
This change introduces reusable buffers, batch-based sample processing, and
separate synchronization mechanisms for estimator lifecycle management and CKMS
sample processing.
## Motivation
Concurrent calls to `MutableQuantiles.add()` contend on a shared monitor.
This limits the scalability of quantile metrics updates when multiple threads
report measurements concurrently.
The objectives are to:
- Reduce contention between concurrent producers.
- Batch incoming samples instead of processing every value individually.
- Reduce unnecessary synchronization in the insertion path.
- Preserve CKMS quantile estimation semantics.
- Maintain correctness during snapshots, rollover, and buffer reuse.
## Implementation
### 1. Buffered ingestion in SampleQuantiles
- Replace `LinkedList` sample storage with `ArrayList`.
- Introduce reusable primitive input buffers.
- Allow producers to append values under a short-lived state lock.
- Hand off full buffers for batch processing.
- Sort incoming batches and merge them into the ordered sample collection.
- Perform CKMS compression after batch insertion.
### 2. Synchronization architecture
The implementation separates synchronization responsibilities:
| Mechanism | Responsibility |
|---|---|
| `stateLock` | Buffer ownership, insertion count, and buffer handoff |
| `flushLock` | Sample merging, CKMS compression, and quantile queries |
| `estimatorLock` | Estimator access, replacement, snapshot coordination,
and rollover |
Normal `SampleQuantiles` insertions use the estimator read lock, while
estimator replacement and lifecycle operations use the write lock.
### 3. Estimator rollover
- Acquire the estimator write lock before replacing the active estimator.
- Create a new estimator for subsequent insertions.
- Snapshot and clear the previous estimator.
- Publish `previousCount` and `previousSnapshot` consistently.
- Coordinate snapshot capture with concurrent insertions and rollover.
### 4. Snapshot and buffer lifecycle
- Drain pending partial batches before producing snapshots.
- Coordinate buffer flushing and CKMS queries.
- Prevent snapshots from observing partially published rollover state.
- Ensure clearing and repeated buffer reuse do not retain stale buffered
values.
## Tests
Added and extended tests in:
- `TestMutableMetrics`
- `TestSampleQuantiles`
Coverage includes:
- Concurrent insertion and snapshot operations.
- Concurrent clear operations.
- Final partial-batch draining.
- Repeated buffer reuse.
- Duplicate values across batch boundaries.
- Estimator lifecycle and rollover behavior.
## Validation
Focused tests executed:
```bash
mvn -pl hadoop-common-project/hadoop-common \
-Dtest=TestSampleQuantiles,TestMutableMetrics \
-Dsurefire.failIfNoSpecifiedTests=false test
```
Previously reported results:
| Test class | Tests passed |
|---|---:|
| TestMutableMetrics | 19 |
| TestSampleQuantiles | 8 |
| Total | 27 |
Failures: 0
Errors: 0
Skipped: 0
Additional validation:
```bash
git diff --check
```
Passed.
Checkstyle was executed using:
```bash
mvn -pl hadoop-common-project/hadoop-common checkstyle:checkstyle
```
The Maven goal completed successfully. The generated report contained
repository-wide violations, so changed-line Checkstyle validation is being used
to isolate issues introduced by this patch.
## Performance evaluation
A production-path JMH benchmark of `MutableQuantiles.add()` was executed
with 1, 4, 8, and 16 producer threads, including workloads with periodic
rollover.
Reported throughput for the modified implementation:
| Workload | Throughput |
|---|---:|
| Add, 1 thread | 1.889M ops/s |
| Add, 4 threads | 1.670M ops/s |
| Add, 8 threads | 1.648M ops/s |
| Add, 16 threads | 1.587M ops/s |
| Add + rollover, 4 threads | 1.663M ops/s |
| Add + rollover, 8 threads | 1.616M ops/s |
A matched benchmark against the original implementation using the same
production-path harness is not yet available. These results therefore describe
the modified implementation and are not presented as a measured percentage
improvement.
## Compatibility
- No intended public API changes.
- Existing quantile estimator behavior is intended to remain compatible.
- No configuration changes are introduced.
## Review notes
The implementation prioritizes synchronization correctness during estimator
replacement and snapshot publication. Rollover retains the estimator write lock
while draining the previous estimator to avoid exposing partially published
state.
Further validation of deterministic rollover interleavings and
baseline-versus-modified performance is important before treating the
optimization as fully benchmark-validated.
> MutableQuantiles.add() causes severe lock contention, blocking all IPC
> Handler threads and degrading RPC performance
> --------------------------------------------------------------------------------------------------------------------
>
> Key: HADOOP-19918
> URL: https://issues.apache.org/jira/browse/HADOOP-19918
> Project: Hadoop Common
> Issue Type: Bug
> Components: hadoop-common, metrics
> Affects Versions: 3.3.3
> Reporter: erzhen wu
> Priority: Major
> Attachments: image-2026-06-11-18-43-36-472.png,
> image-2026-06-11-18-54-43-972.png, image-2026-06-11-18-55-17-240.png
>
>
> h2. Problem Description
> When `rpc.metrics.quantile.enable=true` is enabled in production
> NameNode,
> we observed severe lock contention causing all IPC Handler threads to become
> BLOCKED on `MutableQuantiles.add()`, resulting in:
> * *RpcQueueTimeAvgTime increases significantly* : Requests queuing in
> CallQueue longer
> * *CallQueueLength increases dramatically* :More requests waiting to be
> processed
> * NameNode RPC throughput degradation:Handler threads blocked on metrics
> update
>
> h2. Thread Dump Analysis
> From production NameNode jstack, we found 247 IPC Handler threads
> BLOCKED
> waiting on the same `MutableQuantiles` monitor lock:
> {code:java}
> Thread 283 (IPC Server handler 191 on default port 8020):
> State: BLOCKED
> Blocked count: 15596
> Waited count: 28409
> Blocked on org.apache.hadoop.metrics2.lib.MutableQuantiles@659a2455
> Blocked by 300 (IPC Server handler 208 on default port 8020)
> Stack:
> org.apache.hadoop.metrics2.lib.MutableQuantiles.add(MutableQuantiles.java:133)
>
> org.apache.hadoop.ipc.metrics.RpcMetrics.addRpcQueueTime(RpcMetrics.java:245)
> org.apache.hadoop.ipc.Server.updateMetrics(Server.java:587)
> org.apache.hadoop.ipc.Server$Handler.run(Server.java:3008){code}
> h3. Root Cause
> The `synchronized` keyword on `MutableQuantiles.add()` and
> `SampleQuantiles.insert()`
> creates a global lock contention point:
> {code:java}
> public synchronized void add(long value) {
> estimator.insert(value);
> }
> /**
> * Add a new value from the stream.
> *
> * @param v
> */
> synchronized public void insert(long v) {
> buffer[bufferCount] = v;
> bufferCount++;
> count++;
> if (bufferCount == buffer.length) {
> insertBatch();
> compress();
> }
> } {code}
>
> Lock Contention Chain
> When bufferCount == buffer.length (buffer is full), the thread holding
> the lock executes insertBatch() + compress() which can take milliseconds,
> during which all other Handler threads are BLOCKED:
> {code:java}
> Thread A (holds lock):
> → MutableQuantiles.add()
> → SampleQuantiles.insert()
> → buffer is full (500 elements)
> → insertBatch()
> → compress()
> Thread B, C, D, ... (247 threads):
> → MutableQuantiles.add()
> → BLOCKED waiting for Thread A to release lock
> → Cannot process next RPC request
> → CallQueueLength increases
> → RpcQueueTimeAvgTime increases {code}
> h3. Metrics
> !image-2026-06-11-18-54-43-972.png|width=580,height=247!
> !image-2026-06-11-18-55-17-240.png|width=590,height=246!
> h3. Impact Analysis
>
> The blocking happens in updateMetrics() after RPC processing is
> complete:
> {code:java}
> // Server.java - Handler.run()
>
> void updateMetrics(Call call, long startTime, boolean connDropped) {
> // ...
>
> rpcMetrics.addRpcQueueTime(queueTime); // ← BLOCKS HERE (95% of
> threads)
> rpcMetrics.addRpcLockWaitTime(waitTime);
> rpcMetrics.addRpcProcessingTime(processingTime);
> } {code}
>
> h3. This means:
> # Handler thread completes RPC processing successfully
> # Calls updateMetrics() to report queue time
> # First call addRpcQueueTime() → BLOCKS on MutableQuantiles lock
> # Handler thread cannot process next request in CallQueue
> # CallQueueLength increases as new requests arrive
> # RpcQueueTimeAvgTime increases as requests wait longer in queue
>
>
>
--
This message was sent by Atlassian Jira
(v10.3.26#10030026)
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]