Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Fastapi async coroutines not removed when finished

With the code below, FINISHED coroutines seem never to be removed from the async loop. After every request from a client, an additional coroutine is added to the loop. What is the best way to remove finished coroutines and therefore not running into out of memory problems?

import uvicorn
import asyncio
from loguru import logger

app = FastAPI()
terminate = False

@app.get("/")
async def root():
    return {"message": "Hello World"}

async def print_coroutines():
    global terminate
    while not terminate:
        coroutines = asyncio.Task.all_tasks()
        logger.debug('Total number of coroutines: ' + str(len(coroutines)))
        for coro in coroutines:
            logger.debug(coro)
        await asyncio.sleep(2)

@app.on_event("startup")
async def startup_event():
    asyncio.get_event_loop().create_task(print_coroutines())

@app.on_event("shutdown")
async def shutdown_event():
    global terminate
    terminate = True

if __name__ == "__main__":
    uvicorn.run(app, host="localhost", port=5000)

Console output after opening one browser window:    
  Total number of coroutines: 5
  <Task pending coro=<Server.startup.<locals>.handler() running
  <Task pending coro=<Server.serve() running 
  <Task finished coro=<Server.startup.<locals>.handler() done 
  <Task pending coro=<LifespanOn.main() running
  <Task pending coro=<print_coroutines() running
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!