Skip to content

[fastAPI/Gunicorn]: psycopg2.errors.UniqueViolation: duplicate key value violates unique constraint "pg_type_typname_nsp_index" #1505

Discussion options

You must be logged in to vote

It appears this is a race condition when creating a table (https://www.postgresql.org/message-id/CA+TgmoZAdYVtwBfp1FL2sMZbiHCWT4UPrzRLNnX1Nb30Ku3-gg@mail.gmail.com). I'm not 100% on the right way to fix this but one way is to mov your call to create_db_and_tables into a separate script that's run once before startup. This will create your tables prior to startup after which the program can access them in parallel. One suggestion for a place to do this that would work well with your Docker setup is in a prestart.sh script (https://github.com/tiangolo/uvicorn-gunicorn-docker/blob/master/docker-images/start.sh#L23)

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by YuriiMotov
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
3 participants
Converted from issue

This discussion was converted from issue #138 on August 12, 2025 20:40.