-
Notifications
You must be signed in to change notification settings - Fork 565
[server] Add negative cache for non-existent partition IDs in metadata requests #3511
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
swuferhong
wants to merge
4
commits into
apache:main
Choose a base branch
from
swuferhong:partition-not-exists-cache
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+530
−0
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
130 changes: 130 additions & 0 deletions
130
fluss-server/src/main/java/org/apache/fluss/server/metadata/PartitionNegativeCache.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.fluss.server.metadata; | ||
|
|
||
| import org.apache.fluss.annotation.VisibleForTesting; | ||
| import org.apache.fluss.shaded.guava32.com.google.common.base.Ticker; | ||
| import org.apache.fluss.shaded.guava32.com.google.common.cache.Cache; | ||
| import org.apache.fluss.shaded.guava32.com.google.common.cache.CacheBuilder; | ||
| import org.apache.fluss.utils.clock.Clock; | ||
| import org.apache.fluss.utils.clock.SystemClock; | ||
|
|
||
| import javax.annotation.concurrent.ThreadSafe; | ||
|
|
||
| import java.time.Duration; | ||
|
|
||
| /** | ||
| * A thread-safe negative cache for partition IDs that are known to not exist in ZooKeeper. | ||
| * | ||
| * <p>This cache helps reduce ZooKeeper pressure when clients repeatedly request metadata for | ||
| * partitions that have been deleted (e.g., during hourly partition rotation). Instead of querying | ||
| * ZK every time, we cache the "not exist" result and return it directly. | ||
| * | ||
| * <p>The cache uses access-time-based TTL: entries are evicted after a configurable duration of no | ||
| * access. As long as clients keep asking for the same non-existent partition, the cache entry stays | ||
| * alive and protects ZK. | ||
| */ | ||
| @ThreadSafe | ||
| public class PartitionNegativeCache { | ||
|
|
||
| /** Default TTL for negative cache entries: 10 minutes of no access. */ | ||
| private static final Duration DEFAULT_TTL = Duration.ofMinutes(10); | ||
|
|
||
| /** Default maximum number of negative cache entries. */ | ||
| private static final long DEFAULT_MAXIMUM_SIZE = 10_000L; | ||
|
|
||
| private final Cache<Long, Boolean> cache; | ||
|
|
||
| public PartitionNegativeCache() { | ||
| this(DEFAULT_TTL, DEFAULT_MAXIMUM_SIZE); | ||
| } | ||
|
|
||
| public PartitionNegativeCache(Duration ttl, long maximumSize) { | ||
| this(ttl, maximumSize, SystemClock.getInstance()); | ||
| } | ||
|
|
||
| @VisibleForTesting | ||
| PartitionNegativeCache(Duration ttl, long maximumSize, Clock clock) { | ||
| if (ttl.isZero() || ttl.isNegative()) { | ||
| throw new IllegalArgumentException("TTL must be positive."); | ||
| } | ||
| if (maximumSize <= 0) { | ||
| throw new IllegalArgumentException("Maximum size must be positive."); | ||
| } | ||
| this.cache = | ||
| CacheBuilder.newBuilder() | ||
| .maximumSize(maximumSize) | ||
| .expireAfterAccess(ttl) | ||
| .ticker( | ||
| new Ticker() { | ||
| @Override | ||
| public long read() { | ||
| return clock.nanoseconds(); | ||
| } | ||
| }) | ||
| .build(); | ||
| } | ||
|
|
||
| /** | ||
| * Checks if the given partition ID is known to not exist. | ||
| * | ||
| * <p>If the entry exists and is not expired, Guava refreshes its access time and this method | ||
| * returns {@code true}. If the entry is expired or doesn't exist, returns {@code false}. | ||
| * | ||
| * @param partitionId the partition ID to check | ||
| * @return {@code true} if the partition is known to not exist, {@code false} otherwise | ||
| */ | ||
| public boolean isKnownNonExistent(long partitionId) { | ||
| return cache.getIfPresent(partitionId) != null; | ||
| } | ||
|
|
||
| /** | ||
| * Marks the given partition ID as known to not exist. The entry will remain in the cache until | ||
| * it hasn't been accessed for the configured TTL duration or the bounded cache evicts it. | ||
| * | ||
| * @param partitionId the partition ID to mark as non-existent | ||
| */ | ||
| public void markNonExistent(long partitionId) { | ||
| cache.put(partitionId, Boolean.TRUE); | ||
| } | ||
|
|
||
| /** | ||
| * Marks the given partition ID as existing by removing any stale negative-cache entry. | ||
| * | ||
| * @param partitionId the partition ID to mark as existent | ||
| */ | ||
| public void markExistent(long partitionId) { | ||
| cache.invalidate(partitionId); | ||
| } | ||
|
|
||
| /** | ||
| * Returns the current number of entries in the cache. Includes potentially expired entries that | ||
| * haven't been cleaned up yet. | ||
| */ | ||
| @VisibleForTesting | ||
| public long size() { | ||
| cache.cleanUp(); | ||
| return cache.size(); | ||
| } | ||
|
|
||
| /** Removes all entries from the cache. */ | ||
| @VisibleForTesting | ||
| public void clear() { | ||
| cache.invalidateAll(); | ||
| } | ||
| } |
144 changes: 144 additions & 0 deletions
144
...s-server/src/test/java/org/apache/fluss/server/metadata/PartitionNegativeCacheITCase.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one or more | ||
| * contributor license agreements. See the NOTICE file distributed with | ||
| * this work for additional information regarding copyright ownership. | ||
| * The ASF licenses this file to You under the Apache License, Version 2.0 | ||
| * (the "License"); you may not use this file except in compliance with | ||
| * the License. You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package org.apache.fluss.server.metadata; | ||
|
|
||
| import org.apache.fluss.config.ConfigOptions; | ||
| import org.apache.fluss.exception.PartitionNotExistException; | ||
| import org.apache.fluss.metadata.PartitionSpec; | ||
| import org.apache.fluss.metadata.TableDescriptor; | ||
| import org.apache.fluss.metadata.TablePath; | ||
| import org.apache.fluss.rpc.gateway.CoordinatorGateway; | ||
| import org.apache.fluss.rpc.messages.MetadataRequest; | ||
| import org.apache.fluss.server.testutils.FlussClusterExtension; | ||
|
|
||
| import org.junit.jupiter.api.BeforeAll; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.extension.RegisterExtension; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.Collections; | ||
|
|
||
| import static org.apache.fluss.record.TestData.DATA1_SCHEMA; | ||
| import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createPartition; | ||
| import static org.apache.fluss.server.testutils.RpcMessageTestUtils.createTable; | ||
| import static org.apache.fluss.server.testutils.RpcMessageTestUtils.newDropPartitionRequest; | ||
| import static org.apache.fluss.testutils.common.CommonTestUtils.retry; | ||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.assertj.core.api.Assertions.assertThatThrownBy; | ||
|
|
||
| /** ITCase for {@link PartitionNegativeCache} integration with metadata request processing. */ | ||
| class PartitionNegativeCacheITCase { | ||
|
|
||
| @RegisterExtension | ||
| public static final FlussClusterExtension FLUSS_CLUSTER_EXTENSION = | ||
| FlussClusterExtension.builder().setNumOfTabletServers(1).build(); | ||
|
|
||
| private static CoordinatorGateway coordinatorGateway; | ||
|
|
||
| @BeforeAll | ||
| static void setup() { | ||
| coordinatorGateway = FLUSS_CLUSTER_EXTENSION.newCoordinatorClient(); | ||
| } | ||
|
|
||
| @Test | ||
| void testNegativeCacheForDeletedPartition() throws Exception { | ||
| FLUSS_CLUSTER_EXTENSION.waitUntilAllGatewayHasSameMetadata(); | ||
|
|
||
| // Create a partitioned table with auto-partition disabled. | ||
| TablePath tablePath = TablePath.of("test_db_neg_cache", "partitioned_table"); | ||
| TableDescriptor tableDescriptor = | ||
| TableDescriptor.builder() | ||
| .schema(DATA1_SCHEMA) | ||
| .distributedBy(1) | ||
| .partitionedBy("b") | ||
| .property(ConfigOptions.TABLE_AUTO_PARTITION_ENABLED, false) | ||
| .build(); | ||
| createTable(FLUSS_CLUSTER_EXTENSION, tablePath, tableDescriptor); | ||
|
|
||
| // Create a partition and get its ID. | ||
| String partitionName = "p_to_delete"; | ||
| long partitionId = | ||
| createPartition( | ||
| FLUSS_CLUSTER_EXTENSION, | ||
| tablePath, | ||
| new PartitionSpec(Collections.singletonMap("b", partitionName)), | ||
| false); | ||
|
|
||
| PartitionNegativeCache negativeCache = | ||
| FLUSS_CLUSTER_EXTENSION | ||
| .getCoordinatorServer() | ||
| .getCoordinatorService() | ||
| .getPartitionNegativeCache(); | ||
|
|
||
| // A stale negative-cache entry must not hide a partition that exists in metadata cache. | ||
| MetadataRequest existingPartitionRequest = new MetadataRequest(); | ||
| existingPartitionRequest.addPartitionsId(partitionId); | ||
| existingPartitionRequest | ||
| .addTablePath() | ||
| .setDatabaseName(tablePath.getDatabaseName()) | ||
| .setTableName(tablePath.getTableName()); | ||
| negativeCache.markNonExistent(partitionId); | ||
| retry( | ||
| Duration.ofMinutes(1), | ||
| () -> coordinatorGateway.metadata(existingPartitionRequest).get()); | ||
| assertThat(negativeCache.isKnownNonExistent(partitionId)).isFalse(); | ||
|
|
||
| // Drop the partition. | ||
| coordinatorGateway | ||
| .dropPartition( | ||
| newDropPartitionRequest( | ||
| tablePath, | ||
| new PartitionSpec(Collections.singletonMap("b", partitionName)), | ||
| false)) | ||
| .get(); | ||
|
|
||
| // Wait until the partition is actually deleted from ZK (metadata cache update). | ||
| retry( | ||
| Duration.ofMinutes(1), | ||
| () -> { | ||
| // Request metadata with the deleted partition ID - should throw. | ||
| MetadataRequest request = new MetadataRequest(); | ||
| request.addPartitionsId(partitionId); | ||
| request.addTablePath() | ||
| .setDatabaseName(tablePath.getDatabaseName()) | ||
| .setTableName(tablePath.getTableName()); | ||
| assertThatThrownBy(() -> coordinatorGateway.metadata(request).get()) | ||
| .cause() | ||
| .isInstanceOf(PartitionNotExistException.class); | ||
| assertThat(negativeCache.isKnownNonExistent(partitionId)).isTrue(); | ||
| }); | ||
|
|
||
| // At this point, the partition ID should be in the negative cache. | ||
| // Verify the negative cache is populated on the coordinator. | ||
| assertThat(negativeCache.isKnownNonExistent(partitionId)).isTrue(); | ||
|
|
||
| // Second request should also fail (served from negative cache, no ZK query). | ||
| MetadataRequest secondRequest = new MetadataRequest(); | ||
| secondRequest.addPartitionsId(partitionId); | ||
| secondRequest | ||
| .addTablePath() | ||
| .setDatabaseName(tablePath.getDatabaseName()) | ||
| .setTableName(tablePath.getTableName()); | ||
| assertThatThrownBy(() -> coordinatorGateway.metadata(secondRequest).get()) | ||
| .cause() | ||
| .isInstanceOf(PartitionNotExistException.class); | ||
|
|
||
| // Negative cache should still have the entry. | ||
| assertThat(negativeCache.isKnownNonExistent(partitionId)).isTrue(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Look good to me, only one mirror problem: whether partitionId in partitionIdsNotExistsInCache is included in partitionNegativeCache? If not, this is no need. Maybe this can move blew
partitionIdAndPaths = zkClient.getPartitionIdAndPaths(authorizedTables)for each existed partitionIdAndPaths.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the comment.
partitionIdsNotExistsInCacheindeed does not include IDs already hit by the negative cache.The extra
isPartitionAssignmentMissingFromZk(partitionId)check is still needed before markNonExistent, becausegetPartitionIdAndPaths(authorizedTables)is scoped by the requested/authorized table paths. A miss there may mean the partition belongs to another table or is not visible in this request scope, rather than globally non-existent.I addressed the mirror case by invalidating stale negative-cache entries when we confirm the partition exists:
metadata cache hit: call
partitionNegativeCache.markExistent(partitionId)ZK partitionIdAndPaths hit: call
partitionNegativeCache.markExistent(partitionId)This keeps the negative cache effective for real non-existent partitions while avoiding stale negative entries blocking existing partitions.