Implement an advisory lock to ensure only one application is running with a given configuration
After the configuration is validated but before we set up the publication start a new thread / channel. This thread should be alive while the application is running.
- Open a connection to the PostgreSQL database server.
- Start an advisory lock.
- Ensure that the connection is kept open by periodically sending
SELECT 1
; - If the connection is broken, retry the connection.
Getting an advisory lock:
SET lock_timeout='100ms';
SELECT pg_advisory_lock(123) -- this value will be configurable in the config.yml file
-- Loop here in go and invoke `SELECT 1`
- If the lock acquisition fails (
canceling statement due to lock timeout
) stop the application. - If the
SELECT 1
query fails (connection issue), stop the application. - Add a log entry before invoking the queries (debug level): "Requesting advisory lock (value)"
- Add a log entry after the advisory lock is successfully taken (debug level): "Advisory lock taken (value)"
- For now, hardcode the advisory lock value (
123
) in a variable. This will be configurable.
Note: At a later point we'll implement a retry mechanism so we don't have to stop the application immediately.