How can I trace the cause of a memory spike in Postgres? The title tells the story, but how can I trace the cause of a memory spike in Postgres 11.10? As you can see from the screen shot below there was a memory spike all the way up to 32 GB which caused the OOM to start and kill a bunch of connections. According to /var/log/postgresql/postgresql-11-main.log the database system went into recovery mode at the same time and we lost quite a bit of data as well.
I suspect that the number of connections coupled with very large insert statements might have something to do with it, but need a way of proving (or disproving) the hypothesis.
First, you should configure Linux so that it does not overcommit memory, because there's nothing you can get from a backend that is killed by the OOM killer.
Set vm.overcommit_memory = 2 and set vm.overcommit_ratio to the value calculated as
100 * (RAM - swap) / RAM

Then you should get an OOM error from PostgreSQL rather than PostgreSQL going into crash recovery.
Such an OOM error will cause a memory context dump in the PostgreSQL log file, so you can see which memory context uses all that memory. Also, you get the query that caused the error, so you can experiment with that.