A server with SSH open to the internet gets login attempts constantly. ufw has a rule type for this that most people never use, because allow is the one in every tutorial.
sudo ufw limit ssh
The man page says limit makes ufw deny connections from an address that tries to start 6 or more within 30 seconds. Normal use still gets through. A script that tries passwords as fast as it can does not.
It replaces ufw allow ssh, it does not stack on top of it. If you already have the allow rule, delete it so the limit actually applies, since the allow would match first.
sudo ufw status numbered
Check the result afterwards with the status command. It shows the rule as LIMIT, so you know the change took effect.
Caveat: this is a blunt tool. Many people behind one office or carrier-grade NAT share one address, and a CI job that opens many connections can trip it. And it is no substitute for key-only logins. I would turn off password authentication in sshd as the real fix and treat limit as the cheap extra layer.
Further reading: ufw(8) man page (Ubuntu 24.04), On this site: ufw show added lets you check your rules before you enable the firewall, On this site: ufw status numbered lets you delete a rule by its number