From 88edd54f3ea1e5faaab21cb21e3a7a2fcf9ba96a Mon Sep 17 00:00:00 2001 From: Pierre Ricadat Date: Tue, 26 May 2026 10:01:51 +0900 Subject: [PATCH] Do entity start metric update and expiration fiber start asynchronously to reduce contention --- .../shardcake/internal/EntityManager.scala | 34 +++++++++---------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/entities/src/main/scala/com/devsisters/shardcake/internal/EntityManager.scala b/entities/src/main/scala/com/devsisters/shardcake/internal/EntityManager.scala index 305f22d..15fce5b 100644 --- a/entities/src/main/scala/com/devsisters/shardcake/internal/EntityManager.scala +++ b/entities/src/main/scala/com/devsisters/shardcake/internal/EntityManager.scala @@ -163,23 +163,23 @@ private[shardcake] object EntityManager { ZIO.fail(EntityNotManagedByThisPod(entityId)) case false => // queue doesn't exist, create a new one - for { - queue <- Queue.unbounded[Req] - // start the expiration fiber - expirationFiber <- startExpirationFiber(entityId) - _ <- gauge.increment - _ <- behavior(entityId, queue) - .ensuring( - // shutdown the queue when the fiber ends - entities.update(_ - entityId) *> - gauge.decrement *> - entitiesLastReceivedAt.update(_ - entityId) *> - queue.shutdown *> - expirationFiber.interrupt - ) - .forkDaemon - leftQueue = Left(queue) - } yield (leftQueue, map.updated(entityId, leftQueue)) + Queue.unbounded[Req].flatMap { queue => + val leftQueue = Left(queue) + (for { + // start the expiration fiber + expirationFiber <- startExpirationFiber(entityId) + _ <- gauge.increment + _ <- behavior(entityId, queue) + .ensuring( + // shutdown the queue when the fiber ends + entities.update(_ - entityId) *> + gauge.decrement *> + entitiesLastReceivedAt.update(_ - entityId) *> + queue.shutdown *> + expirationFiber.interrupt + ) + } yield ()).forkDaemon.as((leftQueue, map.updated(entityId, leftQueue))) + } } } )