One thing that is important to remember as a GM is that in table top RPGs there is a big difference between the PCs losing a fight, and the PCs failing a fight.
When the PCs lose a fight, this means they are defeated. The defeat criteria in most RPGs is being reduced to 0 hit points. It is possible the PCs will simply retreat before that happens. Frequently though once the PCs start to lose, they continue to lose until they are all defeated. And this is where TPKs happen.
This makes Encounter Design a balancing act where you want fights to be challenging, but not to cross the line where they wipe the party. You have things like D&D 5e's recommended "encounters per day" and rationing the number of encounters so the PCs have to balance out their resources. But let's be honest, most games I've been in tend to have one big combat a game. Why? Because combat takes a long time. And unless you're playing for 7-12 hours you simply don't have time to track that. Doing 6 encounters in 1 day in 4 hour sessions means that it is going to be 6-12 weeks (depending on how often you do sessions) before that 1 day passes. That is a lot of resource tracking to do. And so most GMs don't bother. Long Rests happen. If for no other reason it feels like forever since the last long rest, and why wouldn't it? It was only an hour in game, but it was 4 weeks ago in real life.
And thus the fine balancing act.
But that is where Failure comes in.
See, I lied in the beginning. It's very hard to Fail a Fight without losing. However, it is very easy to Fail an Encounter without losing. And a fight is an encounter. It's just not the only encounter.
This goes back to the reason for the fight Why are these NPCs fighting the PCs? Are the PCs trying to save hostages? Are the PCs trying to subdue guards before they can alert the castle? Are the NPCs trying to stop the PCs from chasing other NPCs? Is one group, or the other, trying to buy time?
If the purpose of the fight is...just to fight, well, then you have problems as the fail condition is also the lose condition. However, if you have other motivations and goals, then you can give your PCs that defeat and put that in the story without having to fear that it is also a TPK.
The PCs could be trying to stop a ritual. Only they get slowed down getting to the ritual, so it is further along when they arrive. Then some rolls happen and the ritual completes mid combat. Now everything is changing. The ritual is finished. The PCs have failed. But they're not defeated yet.
Now, as a word of warning, it may still feel like a loss at the table. In game the PCs did just lose, they just didn't die. That means it is a loss the story can continue on from. And that can be something very special for a game.