Cavities take time to build up. They don’t just form overnight.
Cavities generally result from laziness or bad technique. You may under-brush your teeth, use weak toothpaste, or ignore flossing and fluoride which provide extra protection against cavities.
The dentist always reminds you of best practices but their words may only be heard twice a year. It’s up to you to keep your teeth healthy.
The good news of course is that cavities can be removed. The bad news is that the procedure is expensive and a little bit painful.
The only thing to do to prevent cavities is to brush daily and in good form. Good habits impede decay. That goes for healthy teeth and just about anything else in life. You have to be consistent.