I've heard it said that the best endings are completely expected and completely a surprise at the same time. Expected, because you, the author, have built a set of promises for the ending over the course of the book, but unexpected, because the characters, and the readers, don't expect how the narrative's promises are going to be fulfilled (even if they already know the ending!).
An interesting and apt example is the movie My Best Friend's Wedding, which (spoiler alert!) is a subversion (bordering on parody) of the popular storyline in which two people belatedly realize they are right for each other. In the film, the protagonist only realizes she "loves" her best friend when he is on the verge of marrying someone else. She sets off to break up the wedding, but realizes, at the very last moment, that he's actually happier with the other woman, and decides to let him be. Throughout the movie, we're given plenty of clues that what the protagonist really needs to do is become happier with herself, and to grow up a little. Her quest is shown to be selfish and narcissistic, and the other woman is consistently portrayed as a lovely woman. By the end, you really don't want the protagonist to succeed, but it creates tension in you, the viewer, because of your expectations (formed through other movies and stories) that the protagonist will get her man, and succeed in her quest. The end is satisfying, even without a love connection, because we get BOTH things we wanted --the protagonist ends up happy, and the wedding doesn't get broken up --and we didn't expect we could get them both at once.
There are a lot of ways to establish your promises for an ending (and a lot of questions and answers dealing with the topic), but some of the main ones are genre-promises (the standard expectations for your genre), foreshadowing (especially important for sad, tragic, or otherwise hard-to-swallow endings), warnings (if the handsome prince kicks a dog, he's not actually going to be the real love interest) and symmetry with the beginning.