ALTER TABLE SET LOGGED locked by autovacuum metrics is an unlogged table that has around 3M rows, I have just executed the ALTER TABLE metrics SET LOGGED to keep this data logged. But it seems to be locked by some autovacuum running process.

  pid  | usename  | blocked_by |              blocked_query
-------+----------+------------+------------------------------------------
 13462 | postgres | {32090}    | ALTER TABLE sensors.metrics SET LOGGED;

    duration     |                                 query                                  |  pid
-----------------+------------------------------------------------------------------------+-------
 02:03:08.131365 | autovacuum: VACUUM pg_toast.pg_toast_315873283 (to prevent wraparound) | 32090


My autovacuum settings for a 32 core and 98gigs RAM:

 autovacuum_max_workers
------------------------
 12
 autovacuum_vacuum_cost_limit
------------------------------
 -1    
 autovacuum_vacuum_cost_delay
------------------------------
 20ms  
 vacuum_cost_page_hit
----------------------
 1
 vacuum_cost_page_miss
-----------------------
 10
 vacuum_cost_page_dirty
------------------------
 20


Can i do something to avoid locking, or fix this locking without terminating a the alter table process that is loggin the data?
You can terminate the autovacuum (32090).  You should not make a habit of doing that, but in this situation it should be OK.

You might want to first run:

select age(relfrozenxid) from pg_class where relname='pg_toast_315873283';


And make sure the reported value is well below 2 billion.

You also might want to check that pg_toast_315873283 is the toast table for sensors.metrics.  I don't see why it would block in the first place were that not the case, but it doesn't hurt to verify those assumptions.

On the other hand, you could just be patient and let the autovacuum finish.  The vacuum needs to happen, and it will generate less WAL traffic if you get the vacuum done while it is still unlogged.

On the third hand, you might want to start a manual VACUUM FREEZE sensors.metrics in one session, and then go cancel both the ALTER TABLE and the autovac, and then do the ALTER TABLE once the vacuum has finished.  This will get done faster than the autovac (the default setting for manual vacuums do not use IO throttling), and again does work that needs to be done eventually and is probably better done while table is still set to UNLOGGED.