I have a hardtail mountain bike and recently I broke the 4 year old chain that I had on it. I’m looking for a new one and I’m wondering how many links I need for a 3x9(27 speed) bike.
Any bike chain you get will have enough links. The only thing to keep an eye on is the number of speeds it is for, which is the chain width. Just make sure you get a 9 speed chain.
There will be a range of lengths of chain that will technically work. A chain is too short if it can not reach around the big cogs on the front and back at the same time. You don't actually want to ever ride like that, but you don't want to break anything by just shifting into the wrong gear combo. A chain is too long if the deraileur can not take up all the slack when you are in both small cogs, or if the chain rubs up against itself because the rear pulley is too far back. Again, you don't want to go around riding in both small cogs, but if the chain becomes slack it can easily slap about and fall off.
The size of the range that will work depends on the difference in cost sizes your gears have, and the length of the derailleur cage. Mountain bikes generally have long-caged derailleurs to accommodate a wider range of cog sizes.
Often, the standard 114 link or so chain is an appropriate size for a mountain bike. If you put it on and it is not too long, you are good to go. But if you are really persnickity you might want to consider whether you want to be closer to too long or closer to too short.
If you are closer to being too short, the chain will actually be under more tension because the deraileur will be slightly more tight at any point than if the chain were longer. Tension in a spring increases as the spring is compressed. If the chain is more tight, it is less likely to bounce off the chainring. So if the terrain is very rough, you might benefit from a tighter chain.
On the other hand, if the chain is closer to being too long, you will be able to easily take a link out of necessary. Often if you break a chain the easiest way to fix it is to just remove a link and reconnect it. If you have sized your chain on the long side, this will be no problem.
As a side note, this is also why it is generally unreliable to just measure a new chain against the old one unless you know for sure that it was sized correctly and never had links removed.