Be consistent: make tactical retreat a normal and important part of play
First, Dungeons & Dragons, particularly later editions, has as the default assumption that a challenge put before players is intended to be one they can overcome, a combat they get in is one they can win. Particularly when that challenge or combat is perceived to be one the DM intended them to get involved in.
So that has to be mitigated, if not eliminated, in the first place. Players have to be used to the idea that tactical retreat is a part of the game and that they aren’t necessarily expected to win every combat. We have a lot of questions about this:
By having these be the “new norm” in your game, it allows you to set up a climactic failure at a pivotal point in the plot.
Supply lesser targets and opportunities for the players to cut their losses
Make sure the players are aware of opportunities to retreat, and also opportunities to mitigate the enemy victory that they cannot prevent. When faced with “our only hope is...” the players are likely to stick with the fight until they die, because there are no other options. The minute chance is better than none. But if it’s increasingly obvious that to continue would be meaninglessly throwing their lives away and there’s something more effective they could be doing, they are much more likely to do that.
Be prepared for deaths
If the moment is critical, it is a point where players are expected to put it all on the line for victory. This is normal and expected: player death is usually problematic, but in this case the death can be rewarding and epic. Even a total party kill could be salvageable here, especially combined with the above where those deaths are not in vain.
In other words, you are talking about a situation where players may choose to die, and that is a good thing.
It helps, in this case, to have as a general rule/suggestion for the game that players have alternate characters ready, or at least concepts for alternate characters. Even better are if there are NPCs that the players are interested/invested in, that they might take over, though that’s kind of rare.
Also, be prepared for an unexpected victory
To be interesting, the fight has to be at least somewhat close. The players have more brains to put together on the problem, and may be able to think of creative solutions you hadn’t considered, or they just may simply get very lucky. Be very careful about “encouraging” results because they are “better” for the plot. It is very easy for a DM to fall into the trap of transforming a game into a story with that line of thinking.