Python Timeout Patterns — ELI5

You’re making toast. You put bread in the toaster and walk away. Normally the toaster pops up after two minutes. But what if it doesn’t? What if the toaster is broken and just keeps heating the bread forever? Eventually you smell smoke.

The fix is simple: you set a kitchen timer. If the toast isn’t done in three minutes, you check on it. You don’t wait forever.

Timeouts are kitchen timers for your code.

When your Python program asks another computer for information — a web page, a database record, an answer from an API — it waits for a response. Usually the response comes back quickly. But sometimes the other computer is slow, overloaded, or completely frozen. Without a timeout, your program just sits there waiting. And waiting. And waiting.

While it waits, it’s stuck. It can’t help other users. It can’t do anything else. If enough requests get stuck waiting, the whole program freezes up.

A timeout says: “I’ll wait 5 seconds. If I don’t get an answer by then, I’ll stop waiting and deal with it.” Maybe that means showing an error message. Maybe it means trying a different server. But at least your program isn’t frozen.

Here’s the tricky part: picking the right number. Too short (half a second) and you’ll give up on things that just needed a little more time. Too long (five minutes) and your users are staring at a spinner. There’s no magic number — it depends on what you’re waiting for.

One thing to remember: A timeout doesn’t fix the slow thing — it protects everything else from being dragged down by it. Always set one.

pythonreliabilityasync

See Also