Fortunately for authors, if a book goes to press and sales do not generate enough royalty to cover the advance, most publishers do not ask you to return the unearned portion. (If your experience has been different, I'd love to hear about it—heave a comment.)
Suppose Madonna gets a $1 million advance on her autobiography but sales are way less than the publisher expected (I know I am not going to buy a copy). Will Madonna have to hand any money back. No.
Bear in mind that I am talking about advances on books that actually go on sale. If you don't deliver a manuscript that meets the publisher's requirements [which are specified in the book contract, which was agreed between you and the publisher] then you may well be asked to return the royalty.
That said, it seems to be a point of honor among publishers not to ask for unearned royalties to be returned if they go through with publication (they figured the sales would be enough to cover it and so asking you for the unearned portion would be a loss of face). I must have written a dozen books that did not earn their advance and never had a request for a refund, so to speak. Some still sit on the publisher's ledger as negative balances.
And here is a lesson: If you are writing a book for money, never count on it earning more than the advance. You simply cannot afford to do that because you are not in charge of the publishing process. This is true however strongly you feel about the book's irresistible appeal to the masses. There is a lot you can do to promote your book. But there is a lot a publisher can neglect to market your book if they lose interest between signing that book contract and printing the first run. Certainly in the field of technical books, publishing houses seem happy to publish a lot of books with mediocre sales, waiting for a break through book to come along. So, write for the advance and the rest is glory or gravy.