You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@celeborn.apache.org by zh...@apache.org on 2023/03/24 09:15:34 UTC

[incubator-celeborn] branch main updated: [CELEBORN-356] [FLINK] Support release single partition resource (#1314)

This is an automated email from the ASF dual-hosted git repository.

zhouky pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/incubator-celeborn.git


The following commit(s) were added to refs/heads/main by this push:
     new 89b3f3887 [CELEBORN-356] [FLINK] Support release single partition resource (#1314)
89b3f3887 is described below

commit 89b3f3887d9b42d04440cc2eadefb79507888bd0
Author: Shuang <lv...@gmail.com>
AuthorDate: Fri Mar 24 17:15:28 2023 +0800

    [CELEBORN-356] [FLINK] Support release single partition resource (#1314)
---
 .../celeborn/plugin/flink/RemoteShuffleMaster.java |  25 +++-
 .../org/apache/celeborn/client/CommitManager.scala |   4 +
 .../apache/celeborn/client/LifecycleManager.scala  |  16 ++-
 .../celeborn/client/ReleasePartitionManager.scala  | 158 +++++++++++++++++++++
 .../celeborn/client/commit/CommitHandler.scala     |  11 +-
 .../client/commit/MapPartitionCommitHandler.scala  |  14 +-
 .../celeborn/client/WithShuffleClientSuite.scala   | 110 ++++++++++----
 .../common/protocol/PartitionLocation.java         |   5 +
 .../org/apache/celeborn/common/CelebornConf.scala  |  30 ++++
 .../common/meta/ShufflePartitionLocationInfo.scala |  56 ++++----
 .../meta/ShufflePartitionLocationInfoSuite.scala   |  89 ++++++++++++
 docs/configuration/client.md                       |   3 +
 .../service/deploy/worker/Controller.scala         |  36 ++---
 .../deploy/worker/storage/StorageManager.scala     |  58 +++++---
 14 files changed, 516 insertions(+), 99 deletions(-)

diff --git a/client-flink/flink-1.14/src/main/java/org/apache/celeborn/plugin/flink/RemoteShuffleMaster.java b/client-flink/flink-1.14/src/main/java/org/apache/celeborn/plugin/flink/RemoteShuffleMaster.java
index 8891d2644..0d220bed8 100644
--- a/client-flink/flink-1.14/src/main/java/org/apache/celeborn/plugin/flink/RemoteShuffleMaster.java
+++ b/client-flink/flink-1.14/src/main/java/org/apache/celeborn/plugin/flink/RemoteShuffleMaster.java
@@ -141,7 +141,30 @@ public class RemoteShuffleMaster implements ShuffleMaster<RemoteShuffleDescripto
 
   @Override
   public void releasePartitionExternally(ShuffleDescriptor shuffleDescriptor) {
-    // TODO
+    executor.execute(
+        () -> {
+          if (!(shuffleDescriptor instanceof RemoteShuffleDescriptor)) {
+            LOG.error(
+                "Only RemoteShuffleDescriptor is supported {}.",
+                shuffleDescriptor.getClass().getName());
+            shuffleMasterContext.onFatalError(
+                new RuntimeException("Illegal shuffle descriptor type."));
+            return;
+          }
+          try {
+            RemoteShuffleDescriptor descriptor = (RemoteShuffleDescriptor) shuffleDescriptor;
+            RemoteShuffleResource shuffleResource = descriptor.getShuffleResource();
+            ShuffleResourceDescriptor resourceDescriptor =
+                shuffleResource.getMapPartitionShuffleDescriptor();
+            LOG.debug("release partition resource: {}.", resourceDescriptor);
+            lifecycleManager.releasePartition(
+                resourceDescriptor.getShuffleId(), resourceDescriptor.getPartitionId());
+          } catch (Throwable throwable) {
+            // it is not a problem if we failed to release the target data partition
+            // because the session timeout mechanism will do the work for us latter
+            LOG.debug("Failed to release data partition {}.", shuffleDescriptor, throwable);
+          }
+        });
   }
 
   @Override
diff --git a/client/src/main/scala/org/apache/celeborn/client/CommitManager.scala b/client/src/main/scala/org/apache/celeborn/client/CommitManager.scala
index b0abfa139..3a183ffe7 100644
--- a/client/src/main/scala/org/apache/celeborn/client/CommitManager.scala
+++ b/client/src/main/scala/org/apache/celeborn/client/CommitManager.scala
@@ -212,6 +212,10 @@ class CommitManager(appId: String, val conf: CelebornConf, lifecycleManager: Lif
         lifecycleManager.recordWorkerFailure(r))
   }
 
+  def releasePartitionResource(shuffleId: Int, partitionId: Int): Unit = {
+    getCommitHandler(shuffleId).releasePartitionResource(shuffleId, partitionId)
+  }
+
   def removeExpiredShuffle(shuffleId: Int): Unit = {
     committedPartitionInfo.remove(shuffleId)
     getCommitHandler(shuffleId).removeExpiredShuffle(shuffleId)
diff --git a/client/src/main/scala/org/apache/celeborn/client/LifecycleManager.scala b/client/src/main/scala/org/apache/celeborn/client/LifecycleManager.scala
index d94bfeba6..b4b7be737 100644
--- a/client/src/main/scala/org/apache/celeborn/client/LifecycleManager.scala
+++ b/client/src/main/scala/org/apache/celeborn/client/LifecycleManager.scala
@@ -126,6 +126,7 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
   private val heartbeater =
     new ApplicationHeartbeater(appId, conf, rssHARetryClient, () => commitManager.commitMetrics())
   private val changePartitionManager = new ChangePartitionManager(conf, this)
+  private val releasePartitionManager = new ReleasePartitionManager(appId, conf, this)
 
   // Since method `onStart` is executed when `rpcEnv.setupEndpoint` is executed, and
   // `rssHARetryClient` is initialized after `rpcEnv` is initialized, if method `onStart` contains
@@ -137,6 +138,7 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
     commitManager.start()
     heartbeater.start()
     changePartitionManager.start()
+    releasePartitionManager.start()
   }
 
   override def onStart(): Unit = {
@@ -172,6 +174,7 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
 
     commitManager.stop()
     changePartitionManager.stop()
+    releasePartitionManager.stop()
     heartbeater.stop()
 
     rssHARetryClient.close()
@@ -982,7 +985,7 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
     success
   }
 
-  private val newLocationFunc =
+  val newLocationFunc =
     new util.function.Function[WorkerInfo, (JList[PartitionLocation], JList[PartitionLocation])] {
       override def apply(w: WorkerInfo): (JList[PartitionLocation], JList[PartitionLocation]) =
         (new util.LinkedList[PartitionLocation](), new util.LinkedList[PartitionLocation]())
@@ -1053,7 +1056,7 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
    * @param slotsToDestroy worker resource to be destroyed
    * @return destroy failed master and slave location unique id
    */
-  private def destroySlotsWithRetry(
+  def destroySlotsWithRetry(
       applicationId: String,
       shuffleId: Int,
       slotsToDestroy: WorkerResource): Unit = {
@@ -1231,6 +1234,15 @@ class LifecycleManager(appId: String, val conf: CelebornConf) extends RpcEndpoin
     workers != null && !workers.isEmpty
   }
 
+  // Once a partition is released, it will be never needed anymore
+  def releasePartition(shuffleId: Int, partitionId: Int): Unit = {
+    releasePartitionManager.releasePartition(shuffleId, partitionId)
+    val partitionLocation = latestPartitionLocation.get(shuffleId)
+    if (partitionLocation != null) {
+      partitionLocation.remove(partitionId)
+    }
+  }
+
   // Initialize at the end of LifecycleManager construction.
   initialize()
 }
diff --git a/client/src/main/scala/org/apache/celeborn/client/ReleasePartitionManager.scala b/client/src/main/scala/org/apache/celeborn/client/ReleasePartitionManager.scala
new file mode 100644
index 000000000..0dd535a2b
--- /dev/null
+++ b/client/src/main/scala/org/apache/celeborn/client/ReleasePartitionManager.scala
@@ -0,0 +1,158 @@
+/*
+ * 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.celeborn.client
+
+import java.util
+import java.util.concurrent.{ConcurrentHashMap, ScheduledExecutorService, ScheduledFuture, TimeUnit}
+
+import scala.collection.JavaConverters._
+import scala.concurrent.duration.DurationInt
+
+import org.apache.celeborn.common.CelebornConf
+import org.apache.celeborn.common.internal.Logging
+import org.apache.celeborn.common.meta.{ShufflePartitionLocationInfo, WorkerInfo}
+import org.apache.celeborn.common.protocol.message.ControlMessages.WorkerResource
+import org.apache.celeborn.common.util.ThreadUtils
+
+class ReleasePartitionManager(
+    appId: String,
+    val conf: CelebornConf,
+    lifecycleManager: LifecycleManager)
+  extends Logging {
+
+  // shuffleId -> (partitionId set of release)
+  private val shuffleReleasePartitionRequests = new ConcurrentHashMap[Int, util.Set[Int]]
+  private val batchHandleReleasePartitionEnabled = conf.batchHandleReleasePartitionEnabled
+  private val batchHandleReleasePartitionExecutors = ThreadUtils.newDaemonCachedThreadPool(
+    "rss-lifecycle-manager-release-partition-executor",
+    conf.batchHandleReleasePartitionNumThreads)
+  private val batchHandleReleasePartitionRequestInterval =
+    conf.batchHandleReleasePartitionRequestInterval
+  private val batchHandleReleasePartitionSchedulerThread: Option[ScheduledExecutorService] =
+    if (batchHandleReleasePartitionEnabled) {
+      Some(ThreadUtils.newDaemonSingleThreadScheduledExecutor(
+        "rss-lifecycle-manager-release-partition-scheduler"))
+    } else {
+      None
+    }
+  private var batchHandleReleasePartition: Option[ScheduledFuture[_]] = _
+
+  def start(): Unit = {
+    batchHandleReleasePartition = batchHandleReleasePartitionSchedulerThread.map {
+      // noinspection ConvertExpressionToSAM
+      _.scheduleAtFixedRate(
+        new Runnable {
+          override def run(): Unit = {
+            try {
+              shuffleReleasePartitionRequests.asScala.foreach {
+                case (shuffleId, unReleasedPartitionIdRequestSet) =>
+                  batchHandleReleasePartitionExecutors.submit {
+                    new Runnable {
+                      override def run(): Unit = {
+                        val unReleasePartitionIds = new util.HashSet[Int]
+                        unReleasedPartitionIdRequestSet.synchronized {
+                          unReleasePartitionIds.addAll(unReleasedPartitionIdRequestSet)
+                          unReleasedPartitionIdRequestSet.clear()
+                        }
+
+                        lifecycleManager.workerSnapshots(shuffleId).asScala.foreach {
+                          case (workerInfo, partitionLocationInfo) =>
+                            val destroyResource = new WorkerResource
+                            unReleasePartitionIds.asScala.foreach {
+                              partitionId =>
+                                addDestroyResource(
+                                  destroyResource,
+                                  workerInfo,
+                                  partitionLocationInfo,
+                                  partitionId)
+                            }
+
+                            if (!destroyResource.isEmpty) {
+                              lifecycleManager.destroySlotsWithRetry(
+                                appId,
+                                shuffleId,
+                                destroyResource)
+                              logTrace(s"Destroyed partition resource for shuffle $shuffleId $destroyResource")
+                            }
+                        }
+                      }
+                    }
+                  }
+              }
+            } catch {
+              case e: InterruptedException =>
+                logError("Partition split scheduler thread is shutting down, detail: ", e)
+                throw e
+            }
+          }
+        },
+        0,
+        batchHandleReleasePartitionRequestInterval,
+        TimeUnit.MILLISECONDS)
+    }
+  }
+
+  def stop(): Unit = {
+    batchHandleReleasePartition.foreach(_.cancel(true))
+    batchHandleReleasePartitionSchedulerThread.foreach(ThreadUtils.shutdown(_, 800.millis))
+  }
+
+  def releasePartition(shuffleId: Int, partitionId: Int): Unit = {
+    if (batchHandleReleasePartitionEnabled) {
+      shuffleReleasePartitionRequests.putIfAbsent(shuffleId, new util.HashSet[Int])
+      val unReleasedPartitionIdRequestSet = shuffleReleasePartitionRequests.get(shuffleId)
+      unReleasedPartitionIdRequestSet.synchronized {
+        unReleasedPartitionIdRequestSet.add(partitionId)
+      }
+    } else {
+      val destroyResource = new WorkerResource
+      lifecycleManager.workerSnapshots(shuffleId).asScala.foreach {
+        case (workerInfo, partitionLocationInfo) =>
+          addDestroyResource(destroyResource, workerInfo, partitionLocationInfo, partitionId)
+      }
+
+      if (!destroyResource.isEmpty) {
+        lifecycleManager.destroySlotsWithRetry(appId, shuffleId, destroyResource)
+        logTrace(
+          s"Destroyed partition resource for partition $shuffleId-$partitionId, $destroyResource")
+      }
+    }
+  }
+
+  private def addDestroyResource(
+      workerResource: WorkerResource,
+      workerInfo: WorkerInfo,
+      partitionLocationInfo: ShufflePartitionLocationInfo,
+      partitionId: Int): Unit = {
+    if (partitionLocationInfo.containsPartition(partitionId)) {
+      val masterLocations = partitionLocationInfo.removeMasterPartitions(partitionId)
+      if (masterLocations != null && !masterLocations.isEmpty) {
+        workerResource.computeIfAbsent(
+          workerInfo,
+          lifecycleManager.newLocationFunc)._1.addAll(masterLocations)
+      }
+
+      val slaveLocations = partitionLocationInfo.removeSlavePartitions(partitionId)
+      if (slaveLocations != null && !slaveLocations.isEmpty) {
+        workerResource.computeIfAbsent(
+          workerInfo,
+          lifecycleManager.newLocationFunc)._2.addAll(slaveLocations)
+      }
+    }
+  }
+}
diff --git a/client/src/main/scala/org/apache/celeborn/client/commit/CommitHandler.scala b/client/src/main/scala/org/apache/celeborn/client/commit/CommitHandler.scala
index d413d0191..7a788343e 100644
--- a/client/src/main/scala/org/apache/celeborn/client/commit/CommitHandler.scala
+++ b/client/src/main/scala/org/apache/celeborn/client/commit/CommitHandler.scala
@@ -218,10 +218,10 @@ abstract class CommitHandler(
         (
           masterParts.asScala
             .filterNot(shuffleCommittedInfo.handledPartitionLocations.contains)
-            .map(_.getUniqueId).asJava,
+            .map(_.getUniqueId).toList.asJava,
           slaveParts.asScala
             .filterNot(shuffleCommittedInfo.handledPartitionLocations.contains)
-            .map(_.getUniqueId).asJava)
+            .map(_.getUniqueId).toList.asJava)
       }
 
       commitFiles(
@@ -462,4 +462,11 @@ abstract class CommitHandler(
   }
 
   def commitMetrics(): (Long, Long) = (totalWritten.sumThenReset(), fileCount.sumThenReset())
+
+  def releasePartitionResource(shuffleId: Int, partitionId: Int): Unit = {
+    val fileGroups = reducerFileGroupsMap.get(shuffleId)
+    if (fileGroups != null) {
+      fileGroups.remove(partitionId)
+    }
+  }
 }
diff --git a/client/src/main/scala/org/apache/celeborn/client/commit/MapPartitionCommitHandler.scala b/client/src/main/scala/org/apache/celeborn/client/commit/MapPartitionCommitHandler.scala
index 297bc5877..8fbfc477a 100644
--- a/client/src/main/scala/org/apache/celeborn/client/commit/MapPartitionCommitHandler.scala
+++ b/client/src/main/scala/org/apache/celeborn/client/commit/MapPartitionCommitHandler.scala
@@ -197,11 +197,6 @@ class MapPartitionCommitHandler(
       recordWorkerFailure(commitFailedWorkers)
     }
 
-    // release resources and clear related info
-    partitionAllocatedWorkers.asScala.foreach { case (_, partitionLocationInfo) =>
-      partitionLocationInfo.removePartitions(partitionId)
-    }
-
     inProcessingPartitionIds.remove(partitionId)
     if (dataCommitSuccess) {
       val resultPartitions =
@@ -226,4 +221,13 @@ class MapPartitionCommitHandler(
       getMapperAttempts(shuffleId),
       succeedPartitionIds))
   }
+
+  override def releasePartitionResource(shuffleId: Int, partitionId: Int): Unit = {
+    val succeedPartitionIds = shuffleSucceedPartitionIds.get(shuffleId)
+    if (succeedPartitionIds != null) {
+      succeedPartitionIds.remove(partitionId)
+    }
+
+    super.releasePartitionResource(shuffleId, partitionId)
+  }
 }
diff --git a/client/src/test/scala/org/apache/celeborn/client/WithShuffleClientSuite.scala b/client/src/test/scala/org/apache/celeborn/client/WithShuffleClientSuite.scala
index 70e802755..d5bdaae47 100644
--- a/client/src/test/scala/org/apache/celeborn/client/WithShuffleClientSuite.scala
+++ b/client/src/test/scala/org/apache/celeborn/client/WithShuffleClientSuite.scala
@@ -17,6 +17,9 @@
 
 package org.apache.celeborn.client
 
+import java.lang
+import java.util.concurrent.Callable
+
 import scala.collection.JavaConverters._
 
 import org.junit.Assert
@@ -24,6 +27,7 @@ import org.junit.Assert
 import org.apache.celeborn.CelebornFunSuite
 import org.apache.celeborn.common.CelebornConf
 import org.apache.celeborn.common.identity.UserIdentifier
+import org.apache.celeborn.common.network.TestUtils
 import org.apache.celeborn.common.util.PackedPartitionId
 
 trait WithShuffleClientSuite extends CelebornFunSuite {
@@ -32,22 +36,27 @@ trait WithShuffleClientSuite extends CelebornFunSuite {
 
   protected val APP = "app-1"
   protected val userIdentifier: UserIdentifier = UserIdentifier("mock", "mock")
-
-  protected lazy val lifecycleManager: LifecycleManager = new LifecycleManager(APP, celebornConf)
-  protected lazy val shuffleClient: ShuffleClientImpl = {
-    val client = new ShuffleClientImpl(celebornConf, userIdentifier)
-    client.setupMetaServiceRef(lifecycleManager.self)
-    client
-  }
-
   private val numMappers = 8
   private val mapId = 1
   private val attemptId = 0
 
+  private var lifecycleManager: LifecycleManager = _
+  private var shuffleClient: ShuffleClientImpl = _
+  private var shuffleId = 0
+
+  override protected def afterEach() {
+    if (lifecycleManager != null) {
+      lifecycleManager.stop()
+    }
+
+    if (shuffleClient != null) {
+      shuffleClient.shutdown()
+    }
+  }
+
   test("test register map partition task") {
-    Assert.assertNotNull(lifecycleManager)
-    Assert.assertNotNull(shuffleClient)
-    val shuffleId = 1
+    prepareService()
+    shuffleId = 1
     var location =
       shuffleClient.registerMapPartitionTask(APP, shuffleId, numMappers, mapId, attemptId)
     Assert.assertEquals(location.getId, PackedPartitionId.packedPartitionId(mapId, attemptId))
@@ -77,16 +86,78 @@ trait WithShuffleClientSuite extends CelebornFunSuite {
     // check all allocated all slots
     partitionLocationInfos = lifecycleManager.workerSnapshots(shuffleId).values().asScala
     logInfo(partitionLocationInfos.toString())
-    count =
-      partitionLocationInfos.map(r => r.getMasterPartitions().size()).sum
+    count = partitionLocationInfos.map(r => r.getMasterPartitions().size()).sum
     Assert.assertEquals(count, numMappers + 1)
   }
 
+  test("test batch release partition") {
+    shuffleId = 2
+    celebornConf.set(CelebornConf.BATCH_HANDLE_RELEASE_PARTITION_ENABLED.key, "true")
+    prepareService()
+    registerAndFinishPartition()
+
+    val partitionLocationInfos = lifecycleManager.workerSnapshots(shuffleId).values().asScala
+
+    // check batch release
+    lifecycleManager.releasePartition(
+      shuffleId,
+      PackedPartitionId.packedPartitionId(mapId, attemptId + 1))
+
+    TestUtils.timeOutOrMeetCondition(new Callable[java.lang.Boolean] {
+      override def call(): lang.Boolean = {
+        partitionLocationInfos.map(r => r.getMasterPartitions().size()).sum == numMappers
+      }
+    })
+  }
+
+  test("test release single partition") {
+    shuffleId = 3
+    celebornConf.set(CelebornConf.BATCH_HANDLE_RELEASE_PARTITION_ENABLED.key, "false")
+    celebornConf.set(CelebornConf.BATCH_HANDLED_RELEASE_PARTITION_INTERVAL.key, "1s")
+    prepareService()
+    registerAndFinishPartition()
+
+    val partitionLocationInfos = lifecycleManager.workerSnapshots(shuffleId).values().asScala
+
+    // check single release
+    lifecycleManager.releasePartition(
+      shuffleId,
+      PackedPartitionId.packedPartitionId(mapId, attemptId + 1))
+
+    Assert.assertEquals(
+      partitionLocationInfos.map(r => r.getMasterPartitions().size()).sum,
+      numMappers)
+  }
+
   test("test map end & get reducer file group") {
-    val shuffleId = 2
+    shuffleId = 4
+    prepareService()
+    registerAndFinishPartition()
+
+    // reduce file group size (for empty partitions)
+    Assert.assertEquals(shuffleClient.getReduceFileGroupsMap.size(), 0)
+
+    // reduce normal empty RssInputStream
+    var stream = shuffleClient.readPartition(APP, shuffleId, 1, 1)
+    Assert.assertEquals(stream.read(), -1)
+
+    // reduce normal null partition for RssInputStream
+    stream = shuffleClient.readPartition(APP, shuffleId, 3, 1)
+    Assert.assertEquals(stream.read(), -1)
+  }
+
+  private def prepareService(): Unit = {
+    lifecycleManager = new LifecycleManager(APP, celebornConf)
+    shuffleClient = new ShuffleClientImpl(celebornConf, userIdentifier)
+    shuffleClient.setupMetaServiceRef(lifecycleManager.self)
+  }
+
+  private def registerAndFinishPartition(): Unit = {
     shuffleClient.registerMapPartitionTask(APP, shuffleId, numMappers, mapId, attemptId)
     shuffleClient.registerMapPartitionTask(APP, shuffleId, numMappers, mapId + 1, attemptId)
     shuffleClient.registerMapPartitionTask(APP, shuffleId, numMappers, mapId + 2, attemptId)
+
+    // task number incr to numMappers + 1
     shuffleClient.registerMapPartitionTask(APP, shuffleId, numMappers, mapId, attemptId + 1)
     shuffleClient.mapPartitionMapperEnd(APP, shuffleId, mapId, attemptId, numMappers, mapId)
     // retry
@@ -102,16 +173,5 @@ trait WithShuffleClientSuite extends CelebornFunSuite {
         .packedPartitionId(mapId, attemptId + 1))
     // another mapper
     shuffleClient.mapPartitionMapperEnd(APP, shuffleId, mapId + 1, attemptId, numMappers, mapId + 1)
-
-    // reduce file group size (for empty partitions)
-    Assert.assertEquals(shuffleClient.getReduceFileGroupsMap.size(), 0)
-
-    // reduce normal empty RssInputStream
-    var stream = shuffleClient.readPartition(APP, shuffleId, 1, 1)
-    Assert.assertEquals(stream.read(), -1)
-
-    // reduce normal null partition for RssInputStream
-    stream = shuffleClient.readPartition(APP, shuffleId, 3, 1)
-    Assert.assertEquals(stream.read(), -1)
   }
 }
diff --git a/common/src/main/java/org/apache/celeborn/common/protocol/PartitionLocation.java b/common/src/main/java/org/apache/celeborn/common/protocol/PartitionLocation.java
index 241d5f48b..a590c16e5 100644
--- a/common/src/main/java/org/apache/celeborn/common/protocol/PartitionLocation.java
+++ b/common/src/main/java/org/apache/celeborn/common/protocol/PartitionLocation.java
@@ -49,6 +49,10 @@ public class PartitionLocation implements Serializable {
     }
   }
 
+  public static String getFileName(String uniqueId, Mode mode) {
+    return uniqueId + "-" + mode.mode();
+  }
+
   private int id;
   private int epoch;
   private String host;
@@ -227,6 +231,7 @@ public class PartitionLocation implements Serializable {
     return id + "-" + epoch;
   }
 
+  /** @see PartitionLocation#getFileName */
   public String getFileName() {
     return id + "-" + epoch + "-" + mode.mode;
   }
diff --git a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
index 30b12eead..a6509ed95 100644
--- a/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
+++ b/common/src/main/scala/org/apache/celeborn/common/CelebornConf.scala
@@ -691,6 +691,10 @@ class CelebornConf(loadDefaults: Boolean) extends Cloneable with Logging with Se
   def batchHandleCommitPartitionEnabled: Boolean = get(BATCH_HANDLE_COMMIT_PARTITION_ENABLED)
   def batchHandleCommitPartitionNumThreads: Int = get(BATCH_HANDLE_COMMIT_PARTITION_THREADS)
   def batchHandleCommitPartitionRequestInterval: Long = get(BATCH_HANDLED_COMMIT_PARTITION_INTERVAL)
+  def batchHandleReleasePartitionEnabled: Boolean = get(BATCH_HANDLE_RELEASE_PARTITION_ENABLED)
+  def batchHandleReleasePartitionNumThreads: Int = get(BATCH_HANDLE_RELEASE_PARTITION_THREADS)
+  def batchHandleReleasePartitionRequestInterval: Long =
+    get(BATCH_HANDLED_RELEASE_PARTITION_INTERVAL)
   def rpcCacheSize: Int = get(RPC_CACHE_SIZE)
   def rpcCacheConcurrencyLevel: Int = get(RPC_CACHE_CONCURRENCY_LEVEL)
   def rpcCacheExpireTime: Long = get(RPC_CACHE_EXPIRE_TIME)
@@ -2414,6 +2418,32 @@ object CelebornConf extends Logging {
       .timeConf(TimeUnit.MILLISECONDS)
       .createWithDefaultString("5s")
 
+  val BATCH_HANDLE_RELEASE_PARTITION_ENABLED: ConfigEntry[Boolean] =
+    buildConf("celeborn.shuffle.batchHandleReleasePartition.enabled")
+      .categories("client")
+      .doc("When true, LifecycleManager will handle release partition request in batch. " +
+        "Otherwise, LifecycleManager will process release partition request immediately")
+      .version("0.3.0")
+      .booleanConf
+      .createWithDefault(false)
+
+  val BATCH_HANDLE_RELEASE_PARTITION_THREADS: ConfigEntry[Int] =
+    buildConf("celeborn.shuffle.batchHandleReleasePartition.threads")
+      .categories("client")
+      .doc("Threads number for LifecycleManager to handle release partition request in batch.")
+      .version("0.3.0")
+      .intConf
+      .createWithDefault(8)
+
+  val BATCH_HANDLED_RELEASE_PARTITION_INTERVAL: ConfigEntry[Long] =
+    buildConf("celeborn.shuffle.batchHandleReleasePartition.interval")
+      .categories("client")
+      .doc(
+        "Interval for LifecycleManager to schedule handling release partition requests in batch.")
+      .version("0.3.0")
+      .timeConf(TimeUnit.MILLISECONDS)
+      .createWithDefaultString("5s")
+
   val REGISTER_SHUFFLE_RPC_ASK_TIMEOUT: OptionalConfigEntry[Long] =
     buildConf("celeborn.rpc.registerShuffle.askTimeout")
       .categories("client")
diff --git a/common/src/main/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfo.scala b/common/src/main/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfo.scala
index c888d7883..43ac809a1 100644
--- a/common/src/main/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfo.scala
+++ b/common/src/main/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfo.scala
@@ -25,10 +25,10 @@ import scala.collection.JavaConverters._
 import org.apache.celeborn.common.protocol.PartitionLocation
 
 class ShufflePartitionLocationInfo {
-
-  type PartitionInfo = ConcurrentHashMap[Int, util.List[PartitionLocation]]
+  type PartitionInfo = ConcurrentHashMap[Int, util.Set[PartitionLocation]]
   private val masterPartitionLocations = new PartitionInfo
   private val slavePartitionLocations = new PartitionInfo
+  implicit val partitionOrdering: Ordering[PartitionLocation] = Ordering.by(_.getEpoch)
 
   def addMasterPartitions(masterLocations: util.List[PartitionLocation]) = {
     addPartitions(masterPartitionLocations, masterLocations)
@@ -38,11 +38,11 @@ class ShufflePartitionLocationInfo {
     addPartitions(slavePartitionLocations, slaveLocations)
   }
 
-  def getMasterPartitions(partitionIdOpt: Option[Int] = None): util.List[PartitionLocation] = {
+  def getMasterPartitions(partitionIdOpt: Option[Int] = None): util.Set[PartitionLocation] = {
     getPartitions(masterPartitionLocations, partitionIdOpt)
   }
 
-  def getSlavePartitions(partitionIdOpt: Option[Int] = None): util.List[PartitionLocation] = {
+  def getSlavePartitions(partitionIdOpt: Option[Int] = None): util.Set[PartitionLocation] = {
     getPartitions(slavePartitionLocations, partitionIdOpt)
   }
 
@@ -51,23 +51,29 @@ class ShufflePartitionLocationInfo {
     slavePartitionLocations.containsKey(partitionId)
   }
 
-  def removePartitions(partitionId: Int): Unit = {
-    masterPartitionLocations.remove(partitionId)
-    slavePartitionLocations.remove(partitionId)
+  def removeMasterPartitions(partitionId: Int): util.Set[PartitionLocation] = {
+    removePartitions(masterPartitionLocations, partitionId)
   }
 
-  def getAllMasterLocationsWithMinEpoch(): util.List[PartitionLocation] = {
-    def order(a: Int, b: Int): Boolean = a < b
+  def removeSlavePartitions(partitionId: Int): util.Set[PartitionLocation] = {
+    removePartitions(slavePartitionLocations, partitionId)
+  }
 
-    masterPartitionLocations.values().asScala.map { list =>
-      var loc = list.get(0)
-      1 until list.size() foreach (ind => {
-        if (order(list.get(ind).getEpoch, loc.getEpoch)) {
-          loc = list.get(ind)
-        }
-      })
-      loc
-    }.toList.asJava
+  private def removePartitions(
+      partitionInfo: PartitionInfo,
+      partitionId: Int): util.Set[PartitionLocation] = {
+    val partitionLocations = partitionInfo.remove(partitionId)
+    if (partitionLocations != null) {
+      partitionLocations
+    } else {
+      new util.HashSet[PartitionLocation]()
+    }
+  }
+
+  def getAllMasterLocationsWithMinEpoch(): util.Set[PartitionLocation] = {
+    masterPartitionLocations.values().asScala.map { partitionLocations =>
+      partitionLocations.asScala.min
+    }.toSet.asJava
   }
 
   private def addPartitions(
@@ -75,20 +81,22 @@ class ShufflePartitionLocationInfo {
       locations: util.List[PartitionLocation]): Unit = synchronized {
     if (locations != null && locations.size() > 0) {
       locations.asScala.foreach { loc =>
-        partitionInfo.putIfAbsent(loc.getId, new util.ArrayList)
-        val locations = partitionInfo.get(loc.getId)
-        locations.add(loc)
+        partitionInfo.putIfAbsent(loc.getId, ConcurrentHashMap.newKeySet())
+        val partitionLocations = partitionInfo.get(loc.getId)
+        if (partitionLocations != null) {
+          partitionLocations.add(loc)
+        }
       }
     }
   }
 
   private def getPartitions(
       partitionInfo: PartitionInfo,
-      partitionIdOpt: Option[Int]): util.List[PartitionLocation] = {
+      partitionIdOpt: Option[Int]): util.Set[PartitionLocation] = {
     partitionIdOpt match {
       case Some(partitionId) =>
-        partitionInfo.getOrDefault(partitionId, new util.ArrayList)
-      case _ => partitionInfo.values().asScala.flatMap(_.asScala).toList.asJava
+        partitionInfo.getOrDefault(partitionId, new util.HashSet)
+      case _ => partitionInfo.values().asScala.flatMap(_.asScala).toSet.asJava
     }
   }
 }
diff --git a/common/src/test/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfoSuite.scala b/common/src/test/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfoSuite.scala
new file mode 100644
index 000000000..3c62ed93c
--- /dev/null
+++ b/common/src/test/scala/org/apache/celeborn/common/meta/ShufflePartitionLocationInfoSuite.scala
@@ -0,0 +1,89 @@
+/*
+ * 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.celeborn.common.meta
+
+import java.util
+
+import org.junit.Assert.{assertEquals, assertTrue}
+
+import org.apache.celeborn.CelebornFunSuite
+import org.apache.celeborn.common.protocol.PartitionLocation
+
+class ShufflePartitionLocationInfoSuite extends CelebornFunSuite {
+
+  test("test operate shuffle partition locations.") {
+    val partitionLocation00 = mockPartition(0, 0)
+    val partitionLocation01 = mockPartition(0, 1)
+    val partitionLocation02 = mockPartition(0, 2)
+    val partitionLocation12 = mockPartition(1, 2)
+    val partitionLocation11 = mockPartition(1, 1)
+
+    val masterLocations = new util.ArrayList[PartitionLocation]()
+    masterLocations.add(partitionLocation00)
+    masterLocations.add(partitionLocation01)
+    masterLocations.add(partitionLocation02)
+    masterLocations.add(partitionLocation11)
+    masterLocations.add(partitionLocation12)
+
+    val slaveLocations = new util.ArrayList[PartitionLocation]()
+    val partitionLocationSlave00 = mockPartition(0, 0)
+    val partitionLocationSlave10 = mockPartition(1, 0)
+    slaveLocations.add(partitionLocationSlave00)
+    slaveLocations.add(partitionLocationSlave10)
+
+    val shufflePartitionLocationInfo = new ShufflePartitionLocationInfo
+    shufflePartitionLocationInfo.addMasterPartitions(masterLocations)
+    shufflePartitionLocationInfo.addSlavePartitions(slaveLocations)
+
+    // test add
+    assertEquals(shufflePartitionLocationInfo.getMasterPartitions().size(), 5)
+    assertEquals(shufflePartitionLocationInfo.getMasterPartitions(Some(0)).size(), 3)
+    assertEquals(shufflePartitionLocationInfo.getMasterPartitions(Some(1)).size(), 2)
+
+    assertEquals(shufflePartitionLocationInfo.getSlavePartitions().size(), 2)
+    assertEquals(shufflePartitionLocationInfo.getSlavePartitions(Some(0)).size(), 1)
+    assertEquals(shufflePartitionLocationInfo.getSlavePartitions(Some(1)).size(), 1)
+
+    // test get min epoch
+    val locations = shufflePartitionLocationInfo.getAllMasterLocationsWithMinEpoch()
+    println(locations)
+    assertTrue(locations.contains(partitionLocation00) && locations.contains(partitionLocation11))
+
+    // test remove
+    assertEquals(shufflePartitionLocationInfo.removeMasterPartitions(0).size(), 3)
+    assertEquals(shufflePartitionLocationInfo.getMasterPartitions().size(), 2)
+    assertEquals(shufflePartitionLocationInfo.getMasterPartitions(Some(1)).size(), 2)
+
+    assertEquals(shufflePartitionLocationInfo.removeSlavePartitions(0).size(), 1)
+    assertEquals(shufflePartitionLocationInfo.getSlavePartitions().size(), 1)
+    assertEquals(shufflePartitionLocationInfo.getSlavePartitions(Some(1)).size(), 1)
+  }
+
+  private def mockPartition(partitionId: Int, epoch: Int): PartitionLocation = {
+    new PartitionLocation(
+      partitionId,
+      epoch,
+      "mock",
+      -1,
+      -1,
+      -1,
+      -1,
+      PartitionLocation.Mode.MASTER)
+  }
+
+}
diff --git a/docs/configuration/client.md b/docs/configuration/client.md
index c63132e3c..ab97f568a 100644
--- a/docs/configuration/client.md
+++ b/docs/configuration/client.md
@@ -59,6 +59,9 @@ license: |
 | celeborn.shuffle.batchHandleCommitPartition.enabled | false | When true, LifecycleManager will handle commit partition request in batch. Otherwise, LifecycleManager won't commit partition before stage end | 0.2.0 | 
 | celeborn.shuffle.batchHandleCommitPartition.interval | 5s | Interval for LifecycleManager to schedule handling commit partition requests in batch. | 0.2.0 | 
 | celeborn.shuffle.batchHandleCommitPartition.threads | 8 | Threads number for LifecycleManager to handle commit partition request in batch. | 0.2.0 | 
+| celeborn.shuffle.batchHandleReleasePartition.enabled | false | When true, LifecycleManager will handle release partition request in batch. Otherwise, LifecycleManager will process release partition request immediately | 0.3.0 | 
+| celeborn.shuffle.batchHandleReleasePartition.interval | 5s | Interval for LifecycleManager to schedule handling release partition requests in batch. | 0.3.0 | 
+| celeborn.shuffle.batchHandleReleasePartition.threads | 8 | Threads number for LifecycleManager to handle release partition request in batch. | 0.3.0 | 
 | celeborn.shuffle.chuck.size | 8m | Max chunk size of reducer's merged shuffle data. For example, if a reducer's shuffle data is 128M and the data will need 16 fetch chunk requests to fetch. | 0.2.0 | 
 | celeborn.shuffle.compression.codec | LZ4 | The codec used to compress shuffle data. By default, Celeborn provides two codecs: `lz4` and `zstd`. | 0.2.0 | 
 | celeborn.shuffle.compression.zstd.level | 1 | Compression level for Zstd compression codec, its value should be an integer between -5 and 22. Increasing the compression level will result in better compression at the expense of more CPU and memory. | 0.2.0 | 
diff --git a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Controller.scala b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Controller.scala
index be887863e..328a87ba0 100644
--- a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Controller.scala
+++ b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/Controller.scala
@@ -588,15 +588,15 @@ private[deploy] class Controller(
 
     // destroy master locations
     if (masterLocations != null && !masterLocations.isEmpty) {
-      masterLocations.asScala.foreach { loc =>
-        val allocatedLoc = partitionLocationInfo.getMasterLocation(shuffleKey, loc)
-        if (allocatedLoc == null) {
-          failedMasters.add(loc)
-        } else {
-          val fileWriter = allocatedLoc.asInstanceOf[WorkingPartition].getFileWriter
-          fileWriter.destroy(
-            new IOException(
-              s"Destroy FileWriter ${fileWriter} caused by receiving Destroy request."))
+      masterLocations.asScala.foreach { uniqueId =>
+        try {
+          storageManager.cleanFile(
+            shuffleKey,
+            PartitionLocation.getFileName(uniqueId, PartitionLocation.Mode.MASTER))
+        } catch {
+          case e: Exception =>
+            failedMasters.add(uniqueId)
+            logDebug(s"Destroy master file $uniqueId for $shuffleKey failed.", e)
         }
       }
       // remove master locations from WorkerInfo
@@ -606,15 +606,15 @@ private[deploy] class Controller(
     }
     // destroy slave locations
     if (slaveLocations != null && !slaveLocations.isEmpty) {
-      slaveLocations.asScala.foreach { loc =>
-        val allocatedLoc = partitionLocationInfo.getSlaveLocation(shuffleKey, loc)
-        if (allocatedLoc == null) {
-          failedSlaves.add(loc)
-        } else {
-          val fileWriter = allocatedLoc.asInstanceOf[WorkingPartition].getFileWriter
-          fileWriter.destroy(
-            new IOException(
-              s"Destroy FileWriter ${fileWriter} caused by receiving Destroy request."))
+      slaveLocations.asScala.foreach { uniqueId =>
+        try {
+          storageManager.cleanFile(
+            shuffleKey,
+            PartitionLocation.getFileName(uniqueId, PartitionLocation.Mode.SLAVE))
+        } catch {
+          case e: Exception =>
+            failedSlaves.add(uniqueId)
+            logDebug(s"Destroy slave file $uniqueId for $shuffleKey failed.", e)
         }
       }
       // remove slave locations from worker info
diff --git a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/storage/StorageManager.scala b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/storage/StorageManager.scala
index e1ac71922..8bd7693b9 100644
--- a/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/storage/StorageManager.scala
+++ b/worker/src/main/scala/org/apache/celeborn/service/deploy/worker/storage/StorageManager.scala
@@ -424,6 +424,40 @@ final private[worker] class StorageManager(conf: CelebornConf, workerSource: Abs
     }.toSeq.sortBy(_._2).reverse.take(conf.metricsAppTopDiskUsageCount * 2).toMap.asJava
   }
 
+  def cleanFile(shuffleKey: String, fileName: String): Unit = {
+    val fileInfo = getFileInfo(shuffleKey, fileName)
+    if (fileInfo != null) {
+      cleanFileInternal(shuffleKey, fileInfo)
+    }
+  }
+
+  def cleanFileInternal(shuffleKey: String, fileInfo: FileInfo): Boolean = {
+    var isHdfsExpired = false
+    if (fileInfo.isHdfs) {
+      isHdfsExpired = true
+      val hdfsFileWriter = hdfsWriters.get(fileInfo.getFilePath)
+      if (hdfsFileWriter != null) {
+        hdfsFileWriter.destroy(new IOException(
+          s"Destroy FileWriter ${hdfsFileWriter} caused by shuffle ${shuffleKey} expired."))
+        hdfsWriters.remove(fileInfo.getFilePath)
+      }
+    } else {
+      val workingDir =
+        fileInfo.getFile.getParentFile.getParentFile.getParentFile
+      val writers = workingDirWriters.get(workingDir)
+      if (writers != null) {
+        val fileWriter = writers.get(fileInfo.getFilePath)
+        if (fileWriter != null) {
+          fileWriter.destroy(new IOException(
+            s"Destroy FileWriter ${fileWriter} caused by shuffle ${shuffleKey} expired."))
+          writers.remove(fileInfo.getFilePath)
+        }
+      }
+    }
+
+    isHdfsExpired
+  }
+
   def cleanupExpiredShuffleKey(expiredShuffleKeys: util.HashSet[String]): Unit = {
     expiredShuffleKeys.asScala.foreach { shuffleKey =>
       logInfo(s"Cleanup expired shuffle $shuffleKey.")
@@ -432,30 +466,10 @@ final private[worker] class StorageManager(conf: CelebornConf, workerSource: Abs
         var isHdfsExpired = false
         if (removedFileInfos != null) {
           removedFileInfos.asScala.foreach {
-            case (_, fileInfo) => {
-              if (fileInfo.isHdfs) {
+            case (_, fileInfo) =>
+              if (cleanFileInternal(shuffleKey, fileInfo)) {
                 isHdfsExpired = true
-                val hdfsFileWriter = hdfsWriters.get(fileInfo.getFilePath)
-                if (hdfsFileWriter != null) {
-                  hdfsFileWriter.destroy(new IOException(
-                    s"Destroy FileWriter ${hdfsFileWriter} caused by shuffle ${shuffleKey} expired."))
-                }
-                fileInfo.deleteAllFiles(StorageManager.hadoopFs)
-                hdfsWriters.remove(fileInfo.getFilePath)
-              } else {
-                val workingDir =
-                  fileInfo.getFile.getParentFile.getParentFile.getParentFile
-                val writers = workingDirWriters.get(workingDir)
-                if (writers != null) {
-                  val fileWriter = writers.get(fileInfo.getFilePath)
-                  if (fileWriter != null) {
-                    fileWriter.destroy(new IOException(
-                      s"Destroy FileWriter ${fileWriter} caused by shuffle ${shuffleKey} expired."))
-                    writers.remove(fileInfo.getFilePath)
-                  }
-                }
               }
-            }
           }
         }
         val (appId, shuffleId) = Utils.splitShuffleKey(shuffleKey)