Postgresql – how to prevent multiple pg_dump to execute at the same time

backuppg-dumppostgresql

I am exposing a REST API to backup a Postgres DB. I have few questions related to that. I have seen most of these questions floating around google but could not find any suitable answer

  1. Is there any way to know the status of the pg_dump? I can redirected the verbose log to the user but somehow I am not convinced with that.
  2. Is there any way to know that a "pg_dump" session is in progress so that I can prevent the user from re-triggering?

Best Answer

You could check if there is running pg_dump process by looking at the pg_stat_activity and also the state of the process:

SELECT 
    pid,
    datname,
    usename,
    state
FROM pg_stat_activity 
WHERE 
    application_name = 'pg_dump';

It would be better if you could also lock some file with your script when you are starting pg_dump and check the lock status of that file when starting new pg_dump to avoid re-triggering.