Sometimes, you write yourself into a corner and the only way to come up with a happy ending is to put a deus ex machina in the end, but the question is whether there's a middle ground and how you can make a deus ex machina more palatable to your audience. For instance, if you decided to foreshadow that deus ex machina or miraculous solution in the last 2 chapter, would that be a good compromise? What are the little things you can do to make it a little better for your readers?
Having asked about deus ex machina sometime ago, I believe that it is 'never' a good idea to include any form of deus ex machina in your story as your readers would just feel that the story ending was 'rushed' (or they'll feel cheated of a decent story.) In other words, it's probably a better idea to not write your characters into a corner such that only a deus ex machina will save them.
That said, if you've included some sort of 'foreshadowing' ahead of time, then I think it's not considered 'technically' deus ex machina. (I could be wrong, I'm still learning).
For instance, a captain of a starship feels they are heading into a trap and calls back to the base for reinforcements and direct them to that waypoint. Afterwards, the ship enters 'hyperspace' and arrives in a middle of a large enemy fleet and starts fighting. In a nick of time, the cavalry arrives. This isn't a deus ex machina (only if there is a plausible explanation of how the captain knows there is a trap ahead; because, if there isn't, the fact that the captain 'knew' without being shown how he knew, would make the reader feel that the captain contacting base for reinforcements would be 'tacked on' action to allow the final cavalry appearance to be 'valid.')
In another instance, a captain of a starship doesn't know they are heading into a trap and his ship exits hyperspace into the middle of an enemy fleet. A battle ensues. The starship is losing and suddenly a huge fleet of friendlies appears and finally beat the enemy. No mention how the huge fleet knew where the captain was. This is a deus ex machina.
With all that said, I'm still learning on this whole deus ex machina concept, so I appreciate pointers throughout my writing.
I have two thoughts.
First, you don't want your deus ex machina to be completely unpredictable. Example: your hero is fighting the villain and is about to lose when suddenly a convenient earthquake strikes. While the villain is trying to regain his footing, your hero beats him. The end.
This is not a satisfying ending because 1) It's pretty obvious that the writer couldn't figure out another way to let the hero win; 2) The reader won't find it fair to have read to the climax and be disappointed when the villain is defeated by a complete coincidence; and 3) It takes the pressure off your hero at the very last moment--i.e., they don't have to do much and yet the villain is destroyed.
Here is how I would fix the scenario above. If there really is no other way than to incorporate a deus ex machina, I would make it less of a random event. Maybe the hero and villain were fighting in a particularly seismic area of the world where earthquakes happened all the time. Maybe the hero knows this and planned on using this fact to surprise his opponent. Here it is much more believable for a deus ex machina-type event to occur. I would not, however, advise you to use a deus ex machina event to completely dismantle the antagonist. At best, it should give the hero an advantage but not guarantee victory. If it does, then it will come as a disappointment to a reader who expects the hero to do the deed, not a completely random event.
My second thought is that it is nearly impossible to configure a plot where the only way out for your protagonist is a deus ex machina. Some of the best books I've ever read had a part where when near the very end everything looked hopeless and the hero had to try to figure out a way to succeed. Keep in mind, you don't want to make victory easy for your main character. This doesn't mean don't give him help, but I would caution you from setting up a deus ex machina to give him victory. A plot twist near the moment of climax can often be just as effective as a deus ex machina, especially if it has been foreshadowed beforehand.
As a general rule: If your plot necessitates a deus ex machina to reach a particular conclusion, your plot probably needs to be changed.
Let me say, however, that this is simply my opinion. There have been many successful books in the past that included deus ex machinae, and I am not an expert. However, it is a difficult plot tool to use well, so I would personally steer clear from using it at the very end of a story.
The first solution to this (and most situations where you've "written yourself into a corner") is - re-write the parts of the story that led to the corner.
You're the writer here, and it's your story - the corner is of your making and it is within your power to make it not exist. It might not be pleasant to do, you might have to significantly re-write whole swathes of your story, and you might have to bin some material you're really proud of in the process. But ultimately prevention is better than cure - if you can avoid the corner in the first place you don't have to answer the deus ex machina question at all.
But what if you can't go back and do a re-write? Maybe you're working in a serialized format and the previous instalments with their inevitable "corner" are already out the door? A deus ex machina is widely reviled, and generally deservedly so - but not always. And the secret here is to do it in such a way that the reader/audience don't even realise it was happening in the first place. So how do you go about doing that?
First rule - the event(s) of the deus ex machina have to be consistent and plausible within the world and narrative you've built. The cavalry coming over the hill, or the arrival of an extra powerful character is only okay if you've already established (a) that such things exist and (b) that they have a plausible reason for being there at that moment. Lay your groundwork correctly here and you don't have a deus ex machina here, but a suitably foreshadowed Big Damn Heroes moment!
Second rule - the event(s) of the deus ex machina shouldn't completely resolve the problem(s). Instead they should provide our heroes with a chance, a chance you can then have them take, but avoid making them irrelevant wherever possible.
Third rule - you can ignore the first two rules if you're using deus ex machina for comic effect. In which case go nuts, hang a lampshade on it. You want the audience to know what you're doing!
Let's look at some examples, good and bad.
Good: Avengers: Endgame - there's two here:
First, the time-travel technology is an admitted one from the writers, they had written themselves into a corner with Infinity War and now they needed a way out. So how does this stack up against our rules? Consistent & Plausible - It's a world where we've already established incredible technology including time travel-adjacent effects have been established. Time-travel magic has already been established. Plus in a world that has superheroes, mutants with powers, magic, aliens, FTL travel etc adding in a bit of time travel isn't a great leap. So I'm calling that a pass on rule 1. Don't completely solve the problem - it gives our heroes a chance, they still have to dig deep and pull off several incredibly challenging missions to make it work, and even then the same tech that gave them that chance gives the antagonist another chance to beat them. So that's a big win on rule 2!
Second, the timely arrival of one Captain Marvel during the large climactic battle. Consistent & Plausible? I'd say yes - we know who Captain Marvel is, she's already been involved with the events of the film and her powers are well established. Don't completely solve the problem - yes again. Her arrival gets the situation back from the brink of completely hopeless into merely "desperate", the other heroes still need to actually win it. The timing of this one is... convenient which has bothered some people but they just about get away with it in my view.
Bad: Raiders of the Lost Ark - there's an actual literal one here!
Our hero (Indiana Jones) is defeated, bound and helpless. The Nazis have won and then... the wrath of God spills out of the titular ark and defeats the Nazis. Yes, really. So, "Consistent & plausible"? Not really, while gods/magic/the supernatural would go on to be part of the Indiana Jones mythos there wasn't anything up to that point that suggested the power of the Ark was real. There's some established lore around the Ark suggesting that eliminating Nazis with extreme prejudice was a thing it can possibly do but it certainly wasn't previously mentioned in the film. "Don't completely solve the problem" - huge failure here, the Ark kills all the bad guys, frees our heroes form their bonds and basically solves everything and practically gift wraps it in the process.
Now I love Raiders - it is a great movie, that's a fun adventure romp with likeable characters and some superb sequences and it thoroughly deserves it's place as a iconic bit of cinema, but it's all of those things in spite of a clumsy bit of deus ex machina right at the end.
Comic effect: Monty Python's Life of Brian
The titular Brian is falling to his certain death - only for a passing alien spaceship to swoop past and catch him. Consistent & plausible? Of course not! It's ancient Judea, but it's also Monty Python, surrealist humour is their stock in trade. Don't completely solve the problem - of course it completely solves the problem. Brian's death is averted and the aliens conveniently remove themselves from the plot to never be mentioned again. Comic effect? Most definitely!
So yes, you can use a deus ex machina and get away with it - but if you can't do it right then it's far better not to do it at all.