I am currently having two Postgresql Clusters attached to my Python FastAPI server
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
primary_engine = create_async_engine("PRIMARY_DATABASE_URL", echo=False, future=True)
replica_engine = create_async_engine("REPLICA_DATABASE_URL", echo=False, future=True)
async def get_primary_session() -> AsyncSession:
async_session = sessionmaker(primary_engine, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session:
yield session
async def get_replica_session() -> AsyncSession:
async_session = sessionmaker(replica_engine, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session:
yield session
Now assume, that the replica crashes. What would be the best strategy to redirect the traffic back to the primary?
I currently have tried this:
async def get_replica_session() -> AsyncSession:
try:
async_session = sessionmaker(replica_engine, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session:
yield session
except:
async_session = sessionmaker(primary_engine, class_=AsyncSession, expire_on_commit=False)
async with async_session() as session:
yield session
However, it used to throw Runtime errors? Hence, it would be great if you could give me some thoughts about it.