psql ^C takes long time to cancel query I am using psql to query a large database. and (understandably) many queries that I type in take a long time.  I typically want to cancel these queries and so I enter ^C, and psql responds with the message

Cancel request sent


This cancel request sometimes cancels queries quickly (milliseconds), but sometimes takes very long times (>10 minutes) to cancel the query and display a prompt where I can type in new commands.  These long cancel times even happen on queries that have only been running less than a second.

Why does psql take so long to cancel some queries?  And what can I do to make psql cancel the queries faster?



Version info:

$ psql --version
psql (PostgreSQL) 10.12 (Ubuntu 10.12-0ubuntu0.18.04.1)
I usually see this when the resultset is large, and has already started to be sent to the client.  The client (apparently, I have not dug into the source code of this) still needs to read everything that was in the pipeline to be sent to it but not yet received, and this can take a long time, especially if the client is in the midst of a swap storm.

Are you using any third party or little-used extensions?

If these aren't the case for you, you will need to provide a reproducer or do some investigation of your own.  While you wait for the cancel to take effect, what is busy on your system?  Just the psql process itself, just the postgres backend it was connected to, or both?  Can you run perf on the busy process and see what it is doing?  Or attach gdb to it and get some backtraces at random times?