feat(pubsub): implement publish hedging to reduce tail latency#13735
feat(pubsub): implement publish hedging to reduce tail latency#13735tonyyyycui wants to merge 12 commits into
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces a hedging mechanism for the Pub/Sub Publisher, adding HedgeSettings for configuration and a thread-safe HedgeTokenBucket to limit hedged requests. The feedback suggests replacing the synchronized methods in HedgeTokenBucket with explicit ReentrantLock to reduce lock contention and improve performance on the critical path.
| import com.google.common.annotations.VisibleForTesting; | ||
| import javax.annotation.concurrent.GuardedBy; | ||
|
|
||
| /** Token bucket for limiting hedged requests. Thread-safe. */ | ||
| final class HedgeTokenBucket { | ||
| private final int maxTokens; | ||
| private final float refillAmount; | ||
|
|
||
| @GuardedBy("this") | ||
| private float tokens; | ||
|
|
||
| HedgeTokenBucket(HedgeSettings settings) { | ||
| this.maxTokens = settings.getMaxTokens(); | ||
| this.refillAmount = settings.getRefill(); | ||
| this.tokens = maxTokens; | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| HedgeTokenBucket(int maxTokens, float refillAmount) { | ||
| this.maxTokens = maxTokens; | ||
| this.refillAmount = refillAmount; | ||
| this.tokens = maxTokens; | ||
| } | ||
|
|
||
| /** | ||
| * Attempts to acquire a token for a hedged request. | ||
| * | ||
| * @return {@code true} if a token was acquired, {@code false} otherwise. | ||
| */ | ||
| synchronized boolean tryAcquire() { | ||
| if (tokens >= 1.0f) { | ||
| tokens -= 1.0f; | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** Refills the bucket by the configured refill amount, capped at max tokens. */ | ||
| synchronized void refill() { | ||
| tokens = Math.min(maxTokens, tokens + refillAmount); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| synchronized float getTokens() { | ||
| return tokens; | ||
| } |
There was a problem hiding this comment.
In performance-sensitive code like the Pub/Sub Publisher, using synchronized methods on the critical path can introduce significant lock contention and performance overhead. To protect shared state while ensuring thread safety and visibility, prefer using explicit locks (such as ReentrantLock) over the synchronized keyword.
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.locks.ReentrantLock;
/** Token bucket for limiting hedged requests. Thread-safe. */
final class HedgeTokenBucket {
private final ReentrantLock lock = new ReentrantLock();
private final int maxTokens;
private final float refillAmount;
private float tokens;
HedgeTokenBucket(HedgeSettings settings) {
this.maxTokens = settings.getMaxTokens();
this.refillAmount = settings.getRefill();
this.tokens = maxTokens;
}
@VisibleForTesting
HedgeTokenBucket(int maxTokens, float refillAmount) {
this.maxTokens = maxTokens;
this.refillAmount = refillAmount;
this.tokens = maxTokens;
}
/**
* Attempts to acquire a token for a hedged request.
*
* @return {@code true} if a token was acquired, {@code false} otherwise.
*/
boolean tryAcquire() {
lock.lock();
try {
if (tokens < 1.0f) {
return false;
}
tokens -= 1.0f;
return true;
} finally {
lock.unlock();
}
}
/** Refills the bucket by the configured refill amount, capped at max tokens. */
void refill() {
lock.lock();
try {
tokens = Math.min((float) maxTokens, tokens + refillAmount);
} finally {
lock.unlock();
}
}
@VisibleForTesting
float getTokens() {
lock.lock();
try {
return tokens;
} finally {
lock.unlock();
}
}References
- In performance-sensitive code, prefer using explicit locks over the 'synchronized' keyword to protect shared state while ensuring thread safety and visibility.
There was a problem hiding this comment.
I think this is a valid concern regarding high contention from the use of synchronized for lock synchronization in this class. I'll take a deeper look on Monday at what better options would be.
michaelpri10
left a comment
There was a problem hiding this comment.
At a higher level, I think the full implementation should be one PR (instead of the , given any submitted changes become public. It would be unexpected for customers to be able to set HedgingSettings without anything actually happening, so the final PR should have everything needed for the implementation included.
| /** Settings for configuring publish hedging. */ | ||
| public final class HedgeSettings { | ||
| /** Default hedging delay. */ | ||
| private static final Duration DEFAULT_DELAY = Duration.ofMillis(100); |
There was a problem hiding this comment.
As a note, this value will be changing (potentially other default values as well). Leaving this as a placeholder comment to ensure these meet the agreed upon values before merging.
There was a problem hiding this comment.
These values should be updated to the defaults of 1s default delay and 50 max tokens.
| * | ||
| * @return the hedging delay. | ||
| */ | ||
| public Duration getHedgeDelay() { |
There was a problem hiding this comment.
nit: Does this method need to be public? I think leaving it without an access modifier (i.e., making it package-private) should be sufficient.
There was a problem hiding this comment.
I've removed it for now, but I think it would also make sense if the user could see what they see the hedge delay is set to since it's a configurable field. Leaving this conversation unresolved.
| import com.google.common.annotations.VisibleForTesting; | ||
| import javax.annotation.concurrent.GuardedBy; | ||
|
|
||
| /** Token bucket for limiting hedged requests. Thread-safe. */ | ||
| final class HedgeTokenBucket { | ||
| private final int maxTokens; | ||
| private final float refillAmount; | ||
|
|
||
| @GuardedBy("this") | ||
| private float tokens; | ||
|
|
||
| HedgeTokenBucket(HedgeSettings settings) { | ||
| this.maxTokens = settings.getMaxTokens(); | ||
| this.refillAmount = settings.getRefill(); | ||
| this.tokens = maxTokens; | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| HedgeTokenBucket(int maxTokens, float refillAmount) { | ||
| this.maxTokens = maxTokens; | ||
| this.refillAmount = refillAmount; | ||
| this.tokens = maxTokens; | ||
| } | ||
|
|
||
| /** | ||
| * Attempts to acquire a token for a hedged request. | ||
| * | ||
| * @return {@code true} if a token was acquired, {@code false} otherwise. | ||
| */ | ||
| synchronized boolean tryAcquire() { | ||
| if (tokens >= 1.0f) { | ||
| tokens -= 1.0f; | ||
| return true; | ||
| } | ||
| return false; | ||
| } | ||
|
|
||
| /** Refills the bucket by the configured refill amount, capped at max tokens. */ | ||
| synchronized void refill() { | ||
| tokens = Math.min(maxTokens, tokens + refillAmount); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| synchronized float getTokens() { | ||
| return tokens; | ||
| } |
There was a problem hiding this comment.
I think this is a valid concern regarding high contention from the use of synchronized for lock synchronization in this class. I'll take a deeper look on Monday at what better options would be.
| /** Settings for configuring publish hedging. */ | ||
| public final class HedgeSettings { | ||
| /** Default hedging delay. */ | ||
| private static final Duration DEFAULT_DELAY = Duration.ofMillis(100); |
There was a problem hiding this comment.
These values should be updated to the defaults of 1s default delay and 50 max tokens.
| import java.time.Duration; | ||
|
|
||
| /** Settings for configuring publish hedging. */ | ||
| public final class HedgeSettings { |
There was a problem hiding this comment.
IIUC, both max tokens and refill ratio will be configurable as well, so setters for this should be added to this class. The constraints should also be enforced in the setters (0.1s <= delay <= 10s, 0 < MaxTokens <= 250, 0 < RefillRatio <= 0.2).
| HedgeTokenBucket(int maxTokens, float refillAmount) { | ||
| this.maxTokens = maxTokens; | ||
| this.refillAmount = refillAmount; | ||
| this.tokens = maxTokens; |
There was a problem hiding this comment.
The token bucket should be empty initially.
| } | ||
| } | ||
|
|
||
| private ApiFuture<PublishResponse> startHedgedCall(final OutstandingBatch outstandingBatch) { |
There was a problem hiding this comment.
Typically the private subclasses are defined last within a Java class, so these methods should be moved above the Builder class definition.
| return DEFAULT_BATCHING_SETTINGS; | ||
| } | ||
|
|
||
| public Publisher build() throws IOException { |
There was a problem hiding this comment.
We should also verify that the per-RPC timeout (InitialRpcTimeoutDuration) is greater than the hedging delay.
|
|
||
| if (!done.get()) { | ||
| lastError.set(t); | ||
| if (runningAttempts.isEmpty() && !isInQueue.get()) { |
There was a problem hiding this comment.
I believe there is a bug here such that if a request fails with a non-retryable error before the hedging delay (e.g., with an INVALID_ARGUMENT error), we will hang until the hedging delay to return the error (and may hedge the request when we shouldn't). For example:
- Publish at t=0ms
- Fails at t=10ms
- isInQueue is still true, so this gets skipped.
- At t=1000ms, processQueue runs
- This can potentially hedge the request again is there are tokens in the bucket
| pubsubMessagesList.add(messageWrapper.getPubsubMessage()); | ||
| } | ||
|
|
||
| outstandingBatch.publishRpcSpan = tracer.startPublishRpcSpan(topicNameObject, messageWrappers); |
There was a problem hiding this comment.
Per the design, we need to update the startPublishRpcSpan method to include "(hedged)" in the publish event on this OTel span.
| private int maxTokens = DEFAULT_MAX_TOKENS; | ||
|
|
||
| /** Refill rate. */ | ||
| private float refill = DEFAULT_REFILL; |
There was a problem hiding this comment.
nit: Lets call this refillRatio to align with the design.
| return false; | ||
| } | ||
|
|
||
| int getAttemptCount() { |
There was a problem hiding this comment.
Annotate this as test-only.
| final int batchSize = outstandingBatch.outstandingPublishes.size(); | ||
| for (final OutstandingPublish outstanding : outstandingBatch.outstandingPublishes) { | ||
| outstanding.publishResult.addListener( | ||
| new Runnable() { |
There was a problem hiding this comment.
I worried that this approach could have cause additional, unneeded overhead. The cancellation check be done in processQueue instead to avoid needing to create these Runnables, but then we run into an issue of the cancellation not propagating to in-flight hedged requests (i.e., publish at t=0, hedge at t=1000, cancellation at t=1050). This may be okay behavior given that cancellations are best effort. I'll raise this issue with the team.
This PR implements publish hedging in the Java Cloud Pub/Sub Publisher. Specifically, it adds support for scheduling "hedged" publish attempts when a publish call is slow to respond. A token-based method is utilized to rate-limit hedged requests and a coordinator is used to manage/cancel concurrent requests to prevent duplicate publishes.