It's a casual way to excuse oneself for a toilet break, mainly used among friends or in relaxed settings, not formal occasions. Can you hold my bag? I'll spend a penny and be right back.
Pro Tip 2/3
British Origin
This phrase is uniquely British, so it might confuse English speakers from other countries where it's not commonly used. When I said I needed to spend a penny, my American friend had no idea I meant using the restroom.
Pro Tip 3/3
Historical Reference
Originally, it referred to inserting a penny into a public toilet lock; understanding this may help remember the phrase. There's no need to spend a penny nowadays; the toilets at the station are free.