In Ruby, don’t use timeout()

  • If all goes well, write the contents of a web page to the database.
  • If the HTTP request fails (e.g., server isn’t listening on port 80), throw an error.
  • If the time spent on the HTTP request plus the time spent writing to the database exceeds five seconds, throw an error and don’t write the row.
  • If the time spent on the HTTP request exceeds five seconds, throw an error and don’t write the row.
  • If the time spent on the database write exceeds five seconds, block until the write finishes (potentially forever), write the row and throw an error.

How Timeout::timeout() works

The idea is simple: Timeout::timeout(X) launches a little thread that sleeps for X seconds and then raises an error in your code.

The consequences

Some libraries, like Ruby’s built-in IO, are written extremely carefully: every single line of code guards against any type of error. You, too, can write your code extremely carefully … but it takes a lot of time and effort.

A better way

Instead, enumerate all the things that can time out and specify them. For instance:

  • If all goes well, write the contents of a web page to the database.
  • If the HTTP request fails (e.g., server isn’t listening on port 80), throw an error.
  • If we lose touch with the HTTP server for five seconds, throw an error.
  • If we lose touch with the database server for three seconds, throw an error.

Refer to the requirements

Our Timeout::timeout() call could take an infinite amount of time writing to the database. This code fixes that error.

Conclusion

If you ever catch yourself writing Timeout::timeout(), stop. Enumerate all the things that might take too long. Solve them one by one.

--

--

Journalist, ex software engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Adam Hooper

Adam Hooper

Journalist, ex software engineer