How to Limit Number of Simultaneous Queries by User in PostgreSQL

limitspostgresqlroleusers

I am looking for way to allow one user to execute maximum 3 queries at the time. Is there such possibility in Postgres?

Due to some technial difficulties I cant limit number of connections, and the solution should be based on limit of simultaneus queries or something similar.

Best Answer

This is not possible now. You have two classes of configuration options

That's all that the server provides. In order to track what you're talking about the server would have to check pg_stat_activity. You can however get the information you're looking for manually..

SELECT usename AS username, count(*) AS concurrent_statements
FROM pg_stat_activity
WHERE state = 'active'
GROUP BY usename;

You can run a function periodically that checks the above and calls pg_cancel_backend(pid int), or pg_terminate_backend(pid int). See the docs here for more information I don't particularly think that's a good idea. I would work with the default options before I tried to roll my own system based on this.