Skip to content

Fallback for Postgresql DB in AsyncSession #518

Open
@junoriosity

Description

@junoriosity

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

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

Description

I am currently having two Postgresql Clusters attached to my Python FastAPI server (see the source code).

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.

Operating System

macOS

Operating System Details

No response

SQLModel Version

0.0.8

Python Version

3.10

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions