Pipped to the Post

What does the idiom “pipped to the post” mean?

Definition: defeated by a narrow margin

Example: The incumbent president was leading for most of the campaign, but he was pipped to the post by the opposition leader in the end.

Note: This idiom is British.