0

I'm new with PostgreSQL and I would like to know or have some leads on:

  • Emit event (call an API) when a table is updated

My problem is: I have a SSO that insert row in an event table when user do something (login, register, update info). I need to exploit these inserts in another solution (a loyalty program) on real time.

For now I have in mind to query the table every minute (in nodeJS) and compare the size of table with the size of the previous minute. I think that is not the good way :)

1 Answer 1

2

You can do that with a trigger in principle. If the API is external to the database, you'd need a trigger function written in C or a language like PL/Perl or PL/Python that can perform the action you need.

However, unless this action can be guaranteed to be fast, it may not be a good idea to run it in a trigger. The trigger runs in the same transaction as the triggering statement, so if your trigger happens to run for a long time, you end up with a long database transaction. This has two main disadvantages:

  • Locks are held for a long time, which harms concurrency and hence performance, and also increases the risk of deadlocks.

  • Autovacuum cannot remove dead rows that were still active when the transaction started, which can lead to excessive table bloat on busy tables.

To avoid that risk, it is often better to use a queuing system: The trigger creates an entry in the queue, which is a fast action, and worker processes read and process these queue entries asynchronously outside the database.

Implementing a queue in a database is notoriously difficult, so you may want to look for existing solutions.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your response. I'll try find an existing solution
PGQ is a famous one, but I have no personal experience with it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.