Skip to content

fix(config): accept multi-host PostgreSQL URLs - #2387

Merged
waketzheng merged 5 commits into
tortoise:developfrom
A-RYAN-1:fix/1924-multi-host-postgres-dsn
Nov 5, 2026
Merged

waketzheng merged 5 commits into
tortoise:developfrom
A-RYAN-1:fix/1924-multi-host-postgres-dsn

Conversation

@A-RYAN-1

Copy link
Copy Markdown
Contributor

Description

Accept libpq style multi-host PostgreSQL URLs, postgres://user:pass@host1:5432,host2:5433/db?target_session_attrs=read-write, for the postgres, postgresql, asyncpg and psycopg schemes. The host part is split on commas, each entry takes its own optional port, and a bare host takes the port from the query string or 5432. A single-host URL gives exactly the same result as before. When a URL lists several hosts, a ?host= value in its query string is ignored.

The clients take the lists as they are for asyncpg, and psycopg joins them with commas for libpq. psycopg also reads target_session_attrs from the URL, which asyncpg already accepted through its connect arguments, so the example above works with both drivers.

Motivation and Context

Fixes #1924. urlparse returns host1,host2 as one hostname, so asyncpg tried to resolve it as a single DNS name and failed with socket.gaierror. psycopg already worked for a shared port (libpq splits the string itself) but not for per-host ports. The closed attempt in #2267 split hosts for asyncpg only; this also covers per-host ports, IPv6 literals, psycopg and the target_session_attrs parameter from the issue's own URL.

How Has This Been Tested?

  • New tests in tests/backends/test_db_url.py (shared port, per-host ports, query parameters, IPv6, the query port as default, invalid port and empty host, other schemes unchanged) and tests/backends/test_connection_params.py (the host and port lists reach asyncpg, the joined strings reach psycopg's conninfo, single-host types stay str and int). Twelve of them fail on develop and all pass with the change.
  • tests/backends on Linux against PostgreSQL 17: 93 passed, 6 skipped, 1 xfailed.
  • Against a real server with a dead first host (host:54399,host:54320), with and without ?target_session_attrs=read-write: asyncpg and psycopg both connect to the second host on Linux. On Windows, psycopg's own connection pool fails the same way with a dead first host outside Tortoise, so that case was not used there.
  • mypy tortoise/backends is clean and ruff reports nothing new on the touched files.

Checklist:

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added the changelog accordingly.
  • I have read the CONTRIBUTING document.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

@codspeed

codspeed Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 21 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 24 untouched benchmarks


Comparing A-RYAN-1:fix/1924-multi-host-postgres-dsn (776dcfd) with develop (cdef122)

Open in CodSpeed

Comment thread CHANGELOG.rst Resolved
@A-RYAN-1

Copy link
Copy Markdown
Contributor Author

Thanks @waketzheng, done: moved to Added, the port check now starts at 1 with the new message, and a test covers port 0.

@A-RYAN-1

A-RYAN-1 commented Nov 1, 2026

Copy link
Copy Markdown
Contributor Author

The three review points are addressed in 9cf39dd (port range starts at 1 with the new message, port 0 test, changelog under Added). Could you re-review and approve the CI run when you have time? Thanks.

A URL such as postgres://u:p@host1,host2:5432/db is libpq's failover
syntax. urlparse reads "host1,host2" back as one hostname, so asyncpg
tried to resolve it as a single DNS name and failed.

Split the host part of postgres, postgresql, asyncpg and psycopg URLs
on commas, each entry with its own optional port (a bare host takes the
port of the query string or 5432), and pass lists to the clients.
asyncpg takes the lists as they are; psycopg gets the comma joined
strings libpq expects. psycopg also reads target_session_attrs from the
URL query, as asyncpg already did through its connect arguments.

Single-host URLs are unchanged.

Fixes tortoise#1924
@A-RYAN-1
A-RYAN-1 force-pushed the fix/1924-multi-host-postgres-dsn branch from 9cf39dd to d560038 Compare November 1, 2026 06:51
- params: replace manual loop with dict(...)
- expand_db_url: use try/except KeyError instead of pre-check + index
- re.match: replace type: ignore with explicit None guard
- DB_LOOKUP: mark Final, restore postgres/postgresql aliases in one line
@A-RYAN-1

A-RYAN-1 commented Nov 2, 2026

Copy link
Copy Markdown
Contributor Author

The changes you asked for are in (port range from 1, test for port 0, changelog under Added). Could you re-run CI and take another look when you have time? Thanks.

@waketzheng

Copy link
Copy Markdown
Contributor

Good job!

Verified multi-host failover on fix/1924-multi-host-postgres-dsn
(asyncpg backend, both local macOS and Docker network):

Test matrix:

  1. All hosts up → connected to primary (first host in list)
  2. primary down → connected to replica-1 (second host)
  3. primary + replica-1 down → connected to replica-2 (third host)

asyncpg traverses the full host list in order, preferring the first reachable
host and gracefully degrading to later hosts when earlier ones are unreachable.

Manually verified using the following steps:

  • docker-compose.yml
services:
  postgres-primary:
    image: postgres:latest
    container_name: tortoise-pg-primary
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: appdb
    ports:
      - "5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
      interval: 3s
      timeout: 3s
      retries: 10
    networks:
      - dbnet

  postgres-replica-1:
    image: postgres:latest
    container_name: tortoise-pg-replica-1
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: appdb
    ports:
      - "5433:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
      interval: 3s
      timeout: 3s
      retries: 10
    networks:
      - dbnet

  postgres-replica-2:
    image: postgres:latest
    container_name: tortoise-pg-replica-2
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres
      POSTGRES_DB: appdb
    ports:
      - "5434:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d appdb"]
      interval: 3s
      timeout: 3s
      retries: 10
    networks:
      - dbnet

  verifier:
    build: .
    container_name: tortoise-multi-host-verifier
    volumes:
      - .:/app
      - /app/.venv
    depends_on:
      postgres-primary:
        condition: service_healthy
      postgres-replica-1:
        condition: service_healthy
      postgres-replica-2:
        condition: service_healthy
    networks:
      - dbnet

networks:
  dbnet:
    driver: bridge
  • Dockerfile
FROM python:3.12-slim

COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /bin/

WORKDIR /app

COPY pyproject.toml uv.lock README.rst ./

ENV UV_PROJECT_ENVIRONMENT="/usr/local"
ENV UV_COMPILE_BYTECODE=1
ENV UV_NO_DEV=1

# Install dependencies
RUN uv sync --frozen --extra asyncpg --no-install-project

COPY tortoise/ ./tortoise/
COPY verify_multi_host.py ./

# Sync the project
RUN uv sync --locked --extra asyncpg

CMD ["python", "verify_multi_host.py"]
  • verify_multi_host.py
import asyncio
import logging
import os
import platform

import tortoise
from tortoise import Model, Tortoise, connections, fields

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("verify-multi-host")


class DummyModel(Model):
    id = fields.IntField(pk=True)
    created_at = fields.DatetimeField(auto_now_add=True, null=True)


# Multi-host DSN: a comma-separated list of host:port pairs.
DEFAULT_DSN = (
    "postgres://postgres:postgres@"
    "postgres-primary,"  # port 5432 can be omitted
    "postgres-replica-1:5433,"
    "postgres-replica-2:5434"
    "/appdb?target_session_attrs=read-write"
)
if platform.system() != "Linux":
    for host in ("postgres-primary", "postgres-replica-1", "postgres-replica-2"):
        DEFAULT_DSN = DEFAULT_DSN.replace(host, "localhost")
else:
    for port in ("5433", "5434"):
        DEFAULT_DSN = DEFAULT_DSN.replace(port, "5432")

MULTI_HOST_DSN = os.getenv("MULTI_HOST_DSN", DEFAULT_DSN)


async def main() -> None:
    logger.info("Tortoise-ORM version: %s", getattr(tortoise, "__version__", "unknown"))
    logger.info("Using multi-host DSN: %s", MULTI_HOST_DSN)

    config = {
        "connections": {"default": MULTI_HOST_DSN},
        "apps": {
            "models": {
                "models": ["__main__"],
                "default_connection": "default",
            }
        },
    }
    await Tortoise.init(config=config)

    try:
        conn = connections.get("default")
        logger.info("Connection pool created. Running verification queries...")

        affected, rows = await conn.execute_query("SELECT 1 AS ping;")
        logger.info("Ping query succeeded: affected=%s rows=%s", affected, rows)

        affected, rows = await conn.execute_query(
            "SELECT "
            "inet_server_addr()::text AS server_addr, "
            "inet_server_port() AS server_port, "
            "current_database() AS db, "
            "current_user AS usr, "
            "pg_backend_pid() AS backend_pid;"
        )
        logger.info("Connected server info: %s", rows)

        logger.info("MULTI-HOST VERIFICATION PASSED")
    except Exception:
        logger.exception("MULTI-HOST VERIFICATION FAILED")
        raise
    finally:
        await Tortoise.close_connections()
        logger.info("Connections closed.")


if __name__ == "__main__":
    asyncio.run(main())
  1. Prepare docker containers and run verifier
    Command:
docker compose up -d --build --wait
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.py

Result:

  • VERIFICATION PASSED
  1. Stop primary host
    Command:
docker compose stop postgres-primary
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.py

Result:

  • VERIFICATION PASSED
  1. Stop replica-1
    Command:
docker compose stop postgres-replica-1
docker compose run --rm --no-deps verifier
uv run --frozen python verify_multi_host.py

Result:

  • VERIFICATION PASSED

@waketzheng
waketzheng merged commit 58f4def into tortoise:develop Nov 5, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Postgres connection string (dsn) with multi-host does not work

2 participants