Skip to content

Commit 5449ecd

Browse files
committed
fix(node): use semaphore to avoid db pool overflow
1 parent c1ce4e2 commit 5449ecd

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

app/jobs/node_checker.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,9 @@ async def initialize_nodes():
126126
async with GetDB() as db:
127127
db_nodes = await get_nodes(db=db, enabled=True)
128128

129+
# Semaphore to limit concurrent node startups to 3 at a time
130+
semaphore = asyncio.Semaphore(3)
131+
129132
async def start_node(node: Node):
130133
try:
131134
await node_manager.update_node(node)
@@ -135,10 +138,14 @@ async def start_node(node: Node):
135138

136139
await node_operator.connect_node(node_id=node.id)
137140

141+
async def start_node_with_limit(node: Node):
142+
async with semaphore:
143+
await start_node(node)
144+
138145
if not db_nodes:
139146
logger.warning("Attention: You have no node, you need to have at least one node")
140147
else:
141-
start_tasks = [start_node(node=db_node) for db_node in db_nodes]
148+
start_tasks = [start_node_with_limit(node=db_node) for db_node in db_nodes]
142149
await asyncio.gather(*start_tasks)
143150
logger.info("All nodes' cores have been started.")
144151

app/operation/node.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,15 @@ async def restart_node(self, node_id: Node, admin: AdminDetails) -> None:
195195

196196
async def restart_all_node(self, db: AsyncSession, admin: AdminDetails, core_id: int | None = None) -> None:
197197
nodes: list[Node] = await self.get_db_nodes(db, core_id)
198-
await asyncio.gather(*[NodeOperation.connect_node(node.id) for node in nodes])
198+
199+
# Semaphore to limit concurrent node restarts to 3 at a time
200+
semaphore = asyncio.Semaphore(3)
201+
202+
async def restart_with_limit(node_id: int):
203+
async with semaphore:
204+
await NodeOperation.connect_node(node_id)
205+
206+
await asyncio.gather(*[restart_with_limit(node.id) for node in nodes])
199207

200208
logger.info(f'All nodes restarted by admin "{admin.username}"')
201209

0 commit comments

Comments
 (0)