You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

切换至Hetzner服务器后Postgres插入速度异常缓慢的排查求助

SQLAlchemy插入Postgres性能骤降排查

背景与测试情况

  • 本地原生Postgres 14环境下,插入120行数据仅需数毫秒
  • 当前Web主机上,Postgres以Docker容器运行并搭配TimescaleDB,插入性能与本地相近,Python脚本部署在同一主机
  • 出于成本考虑切换到Hetzner托管Postgres后,120行插入耗时骤增至10-20秒。脚本部署在美国,托管数据库位于德国,虽存在网络距离,但该性能下降幅度远超预期,最初怀疑是资源不足
  • 验证测试:在Hetzner美国区创建4核8GB配置的云服务器(与当前Web主机配置相近),安装全新Postgres 14并恢复数据库,插入120行耗时5-10秒,仍远低于正常水平
  • 所有测试仅修改SQLAlchemy的Postgres连接字符串,代码完全一致;Hetzner上的数据库通过pg_restore创建,索引、约束等与本地及生产环境完全一致

原插入函数(SQLAlchemy 1.4.43,升级至2.0b3无明显改善)

async def saveSQL(session: AsyncSession, objs: list) -> None:
    '''Params: Async DB Session, list of SQL Alchemy ORM Models'''
    try:
        session.add_all(objs)
        await session.commit()

    except Exception as e:
        logger.exception(f"Exception while saving models to SQL: {e}")

    finally:
        await session.close()

性能优化更新

使用以下语法替代add_all()后,ORM插入性能大幅提升:

async def saveSQL(session: AsyncSession, model: Base, objs: list) -> None:
    '''Params: Async DB Session, the SQLAlchemy Table model, and a list of SQL Alchemy ORM Models'''
    try:
        rows = [dict(obj) for obj in objs]
        await session.scalars(insert(model).returning(model), rows)
        await session.commit()

    except Exception as e:
        logger.exception(f"Exception while saving models to SQL: {e}")

    finally:
        await session.close()

内容的提问来源于stack exchange,提问作者BCC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 18:30:28